ProgrammingHardIBM · Deloitte pattern

What happens when this runs?

What happens when this runs?
int f(void) {
    int x = 5;
    return x;
}
int *g(void) {
    int y = 10;
    return &y;
}
int main(void) {
    int *p = g();
    printf("%d %d", f(), *p);
}
  1. A. 5 10, both guaranteed
  2. B. 5 10, but only by coincidence; *p is undefined behaviour since y's storage no longer belongs to y
  3. C. Compile-time error: g() cannot return the address of a local variable
  4. D. Undefined behaviour affects both f() and g() equally

Correct answer: B. 5 10, but only by coincidence; *p is undefined behaviour since y's storage no longer belongs to y

f() simply returns a copy of x's value, which is perfectly fine and always well-defined. g() returns the ADDRESS of its local y, whose storage is reclaimed the instant g() returns; dereferencing that dangling pointer via *p is undefined behaviour, even though it may 'happen to' still show 10 on many systems since the stack memory hasn't been overwritten yet.

More C Programming questions

Exams that ask this topic