ProgrammingHardTCS NQT · Infosys pattern

What happens?

What happens?
int *p = malloc(sizeof(int));
*p = 10;
free(p);
printf("%d", *p);
  1. A. It always prints 0 because free() zeroes the memory
  2. B. Compilation error: cannot dereference a freed pointer
  3. C. It always prints 10 safely
  4. D. Undefined behaviour: p is a dangling pointer after free(), and dereferencing it (a use-after-free) is not well-defined

Correct answer: D. Undefined behaviour: p is a dangling pointer after free(), and dereferencing it (a use-after-free) is not well-defined

free(p) releases the memory back to the allocator, but p itself still holds the old (now dangling) address; dereferencing it afterward is a use-after-free, classic undefined behaviour that might appear to 'work' by coincidence on some runs but is never guaranteed and is a serious bug class in C.

More C Programming questions

Exams that ask this topic