Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which of the following is true?

  • A."ptr = calloc(m, n)" is equivalent to following
    ptr = malloc(m * n);
  • B."ptr = calloc(m, n)" is equivalent to following
    ptr = malloc(m * n); memset(ptr, 0, m * n);
  • C."ptr = calloc(m, n)" is equivalent to following
    ptr = malloc(m); memset(ptr, 0, m);
  • D."ptr = calloc(m, n)" is equivalent to following
    ptr = malloc(n); memset(ptr, 0, n);

Answer: B

Correct answer: "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m * n); memset(ptr, 0, m * n);

calloc(m, n) does two things: it allocates \( m \times n \) bytes, and it sets every one of them to zero. Reproducing it with malloc therefore needs both steps - the allocation and the memset.

The option offering malloc(m * n) alone gets the size right but leaves the block holding arbitrary data. The two options using m or n alone allocate far too little, since calloc's two arguments are multiplied. That multiplication is also where calloc checks for overflow, which a hand-written product does not.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.