LearnFrenzy
Sign in Take a free test

Pointers · Find the Error · Question 4

Use after free: reading memory after free() in C Answer, explanation & discussion

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

The program below has a problem. 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 = 7;
    free(p);
    printf("%d\n", *p);
    return 0;
}
  • A free(p) must come before *p = 7
  • B The result of malloc() must be cast to (int *)
  • C *p is read after free(p), when the memory no longer belongs to the program Correct
  • D There is no error; it prints 7
Correct Answer: Option C

After free(p) the memory is returned to the allocator, so reading *p is a use-after-free – undefined behaviour. Use the value before freeing, then set p = NULL. (In C the cast on malloc() is not needed.)

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