0

I've read that the difference between calloc and malloc is that calloc initializes the memory to the default value of the type declared.

  1. For struct, what is the default value?
  2. Is there a difference between using calloc and malloc for dynamic array of struct?
  3. Would the members of the struct also be initialized?
1
  • calloc() initializes memory with all bytes zero. So typically all values are initialized zero and all pointers NULL (where NULL is all bytes zero -- which I know of no case that isn't true, but also isn't guaranteed). malloc() does no initialization whatsoever. Commented Oct 17, 2021 at 5:10

2 Answers 2

3

calloc() will initialize the entire allocated memory range to zero. It has nothing to do with what type you are casting to.

malloc() leaves the contents of the memory in an unspecified state.

Sign up to request clarification or add additional context in comments.

Comments

2

The calloc function does not initialize memory to the default value for a given type, and in fact it can't because it knows nothing regarding the type that the memory will be used for.

What it does do is set the memory to all bits 0. On most implementations you're likely to come across, this means that integer and floating point types will have the value 0 and that pointer types will be NULL. With regard to structs and/or arrays, this would apply to any members, and additionally any padding within a struct would also have all bits set to 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.