ProgrammingHardTCS NQT · Infosys pattern
What happens?
What happens?
int *p = malloc(sizeof(int));
*p = 10;
free(p);
printf("%d", *p);- A. It always prints 0 because free() zeroes the memory
- B. Compilation error: cannot dereference a freed pointer
- C. It always prints 10 safely
- 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
- What happens? c int divide(int a, int b) { return a / b; } int main(void) { printf("%d", divide(10, 0)); }
- What is printed? c #define DEBUG 0 int main(void) { #if DEBUG printf("debug moden"); #else printf("release moden"); #endif return 0; }
- Two files are compiled and linked together. What happens? c / file1.c / static int counter = 0; void inc(void) { counter++; } / file2.c /…
- What is printed? c int x = 10; void f(void) { int x = 20; { int x = 30; printf("%d ", x); } printf("%d ", x); } int main(void) { f()…
- What is printed? c void f(void) { register int i; int p = &i; p = 5; printf("%d", i); }
- What is printed? c int x = 100; void f(void) { extern int x; printf("%d", x); } int main(void) { f(); }