ProgrammingHardProduct-company MCQ pattern

What is printed? (undefined behavior aside, assume typical stack layout where locals of adjacent calls can overlap after return)

What is printed? (undefined behavior aside, assume typical stack layout where locals of adjacent calls can overlap after return)
int *dangling(void) {
    int local = 42;
    return &local;
}
int main(void) {
    int *p = dangling();
    int x = 7;
    printf("%d", *p);
}
  1. A. Always prints 42
  2. B. Always prints 7
  3. C. Undefined behavior: p points to a local variable whose lifetime ended when dangling() returned
  4. D. Compilation error: cannot return the address of a local

Correct answer: C. Undefined behavior: p points to a local variable whose lifetime ended when dangling() returned

local's storage duration ends when dangling() returns, so p is a dangling pointer; dereferencing it is undefined behavior even though it compiles cleanly (compilers typically only warn).

More C Programming questions

Exams that ask this topic