简体   繁体   中英

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM