ProgrammingHardTCS NQT · Infosys pattern
What happens when this runs?
What happens when this runs?
void f(int *p) {
free(p);
*p = 10;
}
int main(void) {
int *x = malloc(sizeof(int));
f(x);
printf("done");
}- A. It prints done, and *p=10 is safely ignored after freeing
- B. Undefined behaviour: writing through p after free(p) is a use-after-free
- C. Compile-time error: cannot dereference a pointer immediately after free
- D. It always crashes with a segmentation fault
Correct answer: B. Undefined behaviour: writing through p after free(p) is a use-after-free
free(p) releases the memory back to the allocator, which is free to reuse it for anything; p itself is left dangling (still holding the old address, but no longer owning it). Writing *p = 10 afterward is a use-after-free, undefined behaviour — it may silently corrupt unrelated heap data rather than crash, which is part of what makes this bug dangerous.
More C Programming questions
- What happens when this runs? c int compute(int a, int b) { int result; if (a > b) { result = a - b; } return result; } int main(void) {…
- What happens when this runs? c int makeArray(void) { int local[10]; for (int i = 0; i < 10; i++) local[i] = i; return local; } int…
- What happens when this runs? c int arr[5] = {1, 2, 3, 4, 5}; int p = arr; int val = p[-1]; printf("%d", val);
- What happens when this runs? c int global; int main(void) { printf("%d", global); }
- What happens when this runs? c void fillBuffer(char buf, int size) { for (int i = 0; i <= size; i++) { buf[i] = 'A'; } } int main(void) {…
- What happens when this runs? c int a = 5; int b = a++ + a++ + a++; printf("%d %d", a, b);