LearnFrenzy
Sign in Take a free test

Memory Allocation · Predict the Output · Question 7

free(), set to NULL, free() again – output Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following C program on a 64-bit system?

main.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *p = malloc(sizeof *p);
    free(p);
    p = NULL;
    free(p);
    printf("%s\n", p == NULL ? "safe" : "dangling");
    return 0;
}
  • A safe Correct
  • B dangling
  • C The program crashes with a double free
  • D Compilation error
Correct Answer: Option A

The second free() receives NULL, which is a no-op. Without p = NULL; it would be a double free. (Even if malloc() had failed, freeing NULL is fine.)

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