NewbieToCoding
NewbieToCoding

Reputation: 337

using calloc vs malloc for dynamic array of struct

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?

Upvotes: 0

Views: 437

Answers (2)

dbush
dbush

Reputation: 224387

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.

Upvotes: 2

Bill Lynch
Bill Lynch

Reputation: 81986

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.

Upvotes: 3

Related Questions