ProgrammingHardHCL · Tech Mahindra pattern

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

Assume a 64-bit LP64 ABI. What is printed?
void fillWithPointer(int **pp, int value) {
    *pp = malloc(sizeof(int));
    **pp = value;
}
int main(void) {
    int *p = NULL;
    fillWithPointer(&p, 42);
    printf("%d", *p);
    free(p);
}
  1. A. 0
  2. B. Undefined behaviour: p is never actually changed in main
  3. C. 42
  4. D. NULL pointer dereference

Correct answer: C. 42

Passing &p (a pointer to the pointer p) lets fillWithPointer actually reassign p itself in main, not just a local copy of it. *pp = malloc(...) stores the new heap address into p (through the pointer-to-pointer), and **pp = value writes 42 into that freshly allocated int. Back in main, p now correctly points at that allocated int holding 42.

More C Programming questions

Exams that ask this topic