Question 2
Back to Exercise
The program below has a memory bug. Which statement correctly describes it?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof *p);
if (p == NULL)
return 1;
*p = 5;
printf("%d\n", *p);
free(p);
free(p);
return 0;
}
- A printf() must come after free()
- B p is freed twice; the second free() corrupts the allocator (undefined behaviour) Correct
- C free() needs the size of the block
- D There is no problem
Correct Answer: Option B
Once freed, the block belongs to the allocator again; freeing it a second time is undefined and is a known security exploit. Set p = NULL; after the first free().
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!