ProgrammingHardWipro · Cognizant pattern

What happens when this runs?

What happens when this runs?
int *p = malloc(sizeof(int) * 5);
if (p) {
    for (int i = 0; i < 5; i++) p[i] = i;
}
int *q = realloc(p, sizeof(int) * 10);
if (q) {
    for (int i = 5; i < 10; i++) q[i] = i;
    printf("%d %d", q[0], q[9]);
}
free(q);
  1. A. 0 9
  2. B. Undefined behaviour: p is used after realloc without checking if q == p
  3. C. 0 0
  4. D. Compile-time error: realloc cannot grow an allocation

Correct answer: A. 0 9

realloc either extends the existing block in place or allocates a new block and copies the old contents over (then frees the old one), always returning the valid pointer to use going forward; the first 5 ints (0..4) are preserved by realloc's copy, and the code correctly uses q (not the now-possibly-stale p) afterward. q[0]=0 (preserved), q[9]=9 (newly written).

More C Programming questions

Exams that ask this topic