ProgrammingHardTCS NQT · Infosys pattern
What happens when this runs?
What happens when this runs?
int *p = malloc(sizeof(int));
free(p);
printf("%d", *p);- A. It reliably prints whatever value was last stored there before free
- B. Undefined behaviour: use-after-free, p is now a dangling pointer
- C. Compile-time error: cannot use p after free(p)
- D. It always prints 0
Correct answer: B. Undefined behaviour: use-after-free, p is now a dangling pointer
free(p) returns the memory to the allocator, which may reuse, overwrite, or unmap it at any time; p itself still holds the old address (it is not automatically nulled). Dereferencing it afterward is a classic use-after-free, which is undefined behaviour — the value might coincidentally look unchanged, but relying on that is incorrect and dangerous.
More C Programming questions
- What happens when this runs? c int f(void) { int x = 5; return x; } int g(void) { int y = 10; return &y; } int main(void) { int p = g()…
- What happens when this runs? c char buf[5]; strcpy(buf, "hello world"); printf("%s", buf);
- What happens when this runs? c int divide(int a, int b) { return a / b; } int main(void) { printf("%d", divide(10, 0)); }
- What happens when this runs? c int p = (int )malloc(3 sizeof(int)); if (p == NULL) { return 1; } p[0] = 1; p[1] = 2; p[2] = 3; free(p)…
- What happens when this runs? c int arr[10]; for (int i = 0; i <= 10; i++) { arr[i] = i; } printf("done");
- What is printed? c #define CONCAT(a, b) a##b int main(void) { int xy = 100; printf("%d", CONCAT(x, y)); }