LearnFrenzy
Sign in Take a free test

Memory Allocation · Find the Error · Question 2

Double free of the same pointer in C Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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

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

Post your comment

Comments appear after a quick review by our team.

Popular