ProgrammingHardWipro · Cognizant pattern

What happens when this runs?

What happens when this runs?
int *makeArray(void) {
    int local[10];
    for (int i = 0; i < 10; i++) local[i] = i;
    return local;
}
int main(void) {
    int *arr = makeArray();
    printf("%d", arr[3]);
}
  1. A. 3, guaranteed by the standard
  2. B. Undefined behaviour: local is a stack array whose storage is reclaimed the instant makeArray() returns; arr dangles
  3. C. Compile-time error: cannot return a local array
  4. D. 0, since arrays are always zero when dangling

Correct answer: B. Undefined behaviour: local is a stack array whose storage is reclaimed the instant makeArray() returns; arr dangles

Unlike heap memory from malloc, local (an automatic array) has its storage reclaimed as soon as makeArray() returns — the compiler would actually warn about returning the address of a local variable here. Dereferencing arr afterward is undefined behaviour; it may appear to 'still work' by luck since nothing has overwritten that stack memory yet, but this is never guaranteed.

More C Programming questions

Exams that ask this topic