ProgrammingHardTCS NQT · Infosys pattern
What is the behavior?
What is the behavior?
int *p = malloc(10 * sizeof(int));
free(p);
printf("%d", p[0]);- A. Guaranteed to print whatever was last stored there
- B. Undefined behavior: p is a dangling pointer after free, and p[0] is a use-after-free read
- C. Guaranteed to print 0
- 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
- What is printed? c int i = 1; int arr[5] = {0}; int x = i + i++; printf("%d", x);
- What is the behavior? c int arr[5] = {1,2,3,4,5}; int p = arr + 5; printf("%p", (void)p); printf("%d", p);
- What is the behavior? c char buf[5]; strcpy(buf, "hello world"); printf("%s", buf);
- What is the behavior? c int a = 10; int b = a << 32; printf("%d", b);
- What is the behavior? c const int x = 10; int p = (int)&x; p = 20; printf("%d", x);
- What is the behavior? c int a[3] = {1, 2, 3}; memcpy(a, a + 1, 2 sizeof(int)); printf("%d %d %d", a[0], a[1], a[2]);