LearnFrenzy
Sign in Take a free test

Memory Allocation · Predict the Output · Question 2

calloc() then realloc() – which values survive? Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following C program on a 64-bit system?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links