Question 2
Back to Exercise
What is the output of the following C program on a 64-bit system?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = calloc(3, sizeof *a);
if (a == NULL)
return 1;
a[0] = 7;
int *b = realloc(a, 5 * sizeof *a);
if (b == NULL) {
free(a);
return 1;
}
b[4] = 9;
printf("%d %d %d\n", b[0], b[2], b[4]);
free(b);
return 0;
}
- A 7 0 9 Correct
- B 7 garbage 9
- C 0 0 9
- D 7 0 0
Correct Answer: Option A
realloc() keeps the old contents: b[0] = 7 and b[2] = 0 (from calloc). The two new elements are uninitialised; b[4] is set before it is read, and b[3] is never read.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!