ProgrammingHardHCL · Tech Mahindra pattern

Assume a 64-bit LP64 ABI. What happens?

Assume a 64-bit LP64 ABI. What happens?
int *createArray(int n) {
    int arr[n];
    for (int i = 0; i < n; i++) arr[i] = i * i;
    return arr;
}
int main(void) {
    int *p = createArray(5);
    printf("%d", p[2]);
}
  1. A. 4
  2. B. Undefined behaviour: arr is a variable-length array with automatic storage, and returning its address gives a dangling pointer once createArray returns
  3. C. 0
  4. D. Compilation error: cannot return a VLA

Correct answer: B. Undefined behaviour: arr is a variable-length array with automatic storage, and returning its address gives a dangling pointer once createArray returns

arr is a variable-length array (VLA) with automatic (stack) storage duration local to createArray; returning `arr` (which decays to a pointer to its first element) gives the caller a pointer into a stack frame that no longer exists once the function returns — classic dangling pointer UB, not a guaranteed 4.

More C Programming questions

Exams that ask this topic