ProgrammingHardHCL · Tech Mahindra pattern

Assume a 64-bit LP64 ABI. What happens when this runs?

Assume a 64-bit LP64 ABI. What happens when this runs?
int *create(void) {
    int x = 42;
    return &x;
}
int main(void) {
    int *p = create();
    printf("%d", *p);
}
  1. A. It prints 0
  2. B. Compile-time error: cannot return the address of a local variable
  3. C. It prints 42, guaranteed by the C standard
  4. D. Undefined behaviour: p is a dangling pointer to x's destroyed stack frame

Correct answer: D. Undefined behaviour: p is a dangling pointer to x's destroyed stack frame

x is a local (automatic) variable whose storage is reclaimed as soon as create() returns. The returned pointer dangles, pointing at memory that is no longer reserved for x; dereferencing it is undefined behaviour (it may happen to print 42 on some setups, but that is not guaranteed and is not something to rely on).

More C Programming questions

Exams that ask this topic