Home > Software engineering >  using calloc vs malloc for dynamic array of struct
using calloc vs malloc for dynamic array of struct

Time:10-17

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?

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

calloc() will initialize the entire allocated memory range to zero. It has nothing to do with what type you are casting to. ​ ​Malloc() function will create a single block of memory of size specified by the user. Calloc() function can assign multiple blocks of memory for a variable. Malloc function contains garbage value. The memory block allocated by a calloc function is always initialized to zero. ​

  •  Tags:  
  • c
  • Related