ProgrammingHardTCS NQT · Infosys pattern

What is the behavior?

What is the behavior?
int *p = malloc(10 * sizeof(int));
free(p);
printf("%d", p[0]);
  1. A. Guaranteed to print whatever was last stored there
  2. B. Undefined behavior: p is a dangling pointer after free, and p[0] is a use-after-free read
  3. C. Guaranteed to print 0
  4. D. Compilation error

Correct answer: B. Undefined behavior: p is a dangling pointer after free, and p[0] is a use-after-free read

free(p) releases the memory back to the allocator; p itself still holds the old address (a dangling pointer), and reading through it afterward (use-after-free) is undefined behavior — the memory may be reused by another allocation at any time.

More C Programming questions

Exams that ask this topic