ProgrammingHardWipro · Cognizant pattern

What happens?

What happens?
int *getDangling(void) {
    int local = 42;
    return &local;
}
int main(void) {
    int *p = getDangling();
    printf("%d", *p);
}
  1. A. It always prints 42 reliably
  2. B. Undefined behaviour: p is a dangling pointer to a local variable whose stack frame no longer exists after getDangling() returns
  3. C. Compilation error: cannot return the address of a local variable
  4. D. It always prints 0

Correct answer: B. Undefined behaviour: p is a dangling pointer to a local variable whose stack frame no longer exists after getDangling() returns

`local` has automatic storage duration tied to getDangling()'s stack frame, which is destroyed/invalidated once the function returns; p then points to memory that is no longer reserved for `local` (and may be reused by any later call), making *p undefined behaviour — it might coincidentally still show 42 on some runs, but this is never guaranteed.

More C Programming questions

Exams that ask this topic