ProgrammingHardIBM · Deloitte pattern

Assume a 64-bit LP64 ABI. What is printed?

Assume a 64-bit LP64 ABI. What is printed?
int *allocateArray(int n) {
    int *arr = malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) arr[i] = i * i;
    return arr;
}
int main(void) {
    int *squares = allocateArray(5);
    printf("%d %d %d", squares[0], squares[2], squares[4]);
    free(squares);
}
  1. A. 0 2 4
  2. B. Undefined behaviour: arr is local to allocateArray and dangles after it returns
  3. C. 0 4 16
  4. D. Compile-time error: cannot return a malloc'd pointer from a function

Correct answer: C. 0 4 16

Unlike returning the address of a STACK (automatic) local variable, arr here points at HEAP memory obtained via malloc, which remains valid and accessible until explicitly freed, regardless of which function's scope created the pointer. Returning that pointer is completely safe and a standard idiom. squares[i] = i*i gives 0, 4, 16 for i=0,2,4.

More C Programming questions

Exams that ask this topic