Question 5
Back to Exercise
The program below has a memory bug. Which statement correctly describes it?
#include <stdlib.h>
int main(void) {
int x = 10;
int *p = &x;
free(p);
return 0;
}
- A p points to a stack variable; free() may only receive pointers from malloc/calloc/realloc Correct
- B x must be initialised with malloc first
- C free() needs a cast to void *
- D There is no problem
Correct Answer: Option A
Stack memory is released automatically when the function returns. Passing its address to free() is undefined behaviour; compilers warn and AddressSanitizer reports "attempting free on address which was not malloc()-ed".
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!