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);
}- A. 0 2 4
- B. Undefined behaviour: arr is local to allocateArray and dangles after it returns
- C. 0 4 16
- 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
- Assume a 64-bit LP64 ABI. What is printed? c int compare(const void a, const void b) { return (const int )a - (const int )b; } int…
- Assume a 64-bit LP64 ABI. What is printed? c void fillWithPointer(int pp, int value) { pp = malloc(sizeof(int)); pp = value; } int…
- Assume a 64-bit LP64 ABI. What is printed? c char str[] = "hello"; char p = str; while (p != '0') { p = p - 32; p++; } printf("%s", str);
- Assume a 64-bit LP64 ABI. What happens when this runs? c char str = "hello"; str[0] = 'H'; printf("%s", str);
- Assume a 64-bit LP64 ABI. What is printed? c struct Flags { unsigned isActive : 1; unsigned isAdmin : 1; unsigned level : 6; }; struct…
- Assume a 64-bit LP64 ABI. What is printed? c union Data { int i; char c; }; union Data d; d.i = 0x12345678; printf("%x", (unsigned…