LearnFrenzy
Sign in Take a free test

Memory Allocation · Find the Error · Question 5

Error: freeing the address of a local variable Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program below has a memory bug. Which statement correctly describes it?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links