ProgrammingHardTCS NQT · Infosys pattern

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

Assume a 64-bit LP64 ABI. What is printed?
int *createZeroed(int n) {
    int *arr = calloc(n, sizeof(int));
    return arr;
}
int main(void) {
    int *arr = createZeroed(5);
    printf("%d %d %d", arr[0], arr[2], arr[4]);
    free(arr);
}
  1. A. 0 0 0
  2. B. Undefined behaviour: calloc does not guarantee zero-initialisation
  3. C. Garbage garbage garbage
  4. D. 1 1 1

Correct answer: A. 0 0 0

Unlike malloc, calloc is specifically guaranteed by the C standard to zero-initialise the entire allocated block. Every element of the returned array is reliably 0 until explicitly written, so arr[0], arr[2], arr[4] all print 0.

More C Programming questions

Exams that ask this topic