简体   繁体   中英

What's the default value in an array after using malloc on a struct in C

Suppose I have this code:

typedef char BLOCK[10];
typedef struct {
  BLOCK block;
}Object;

And I do this:

Object* obj;
obj = malloc(sizeof(obj));

My question:
Will the array "block" have a default value in each of its cell?

Assuming the 'error' in your code is just a typo (it should be obj = malloc(sizeof(*obj)); or you will allocate enough space to hold a pointer ), then there is nothing in the Standard(s) to specify what the allocated data will initialized to.

If you want defined initialisation behaviour, then you can use calloc :

obj = calloc(1, sizeof(*obj)); // Note: sizeof(obj) = pointer size but sizeof(*obj) is struct size

which will initialize all allocated bytes to zero.

malloc() doesn't initialize the allocated memory. See man malloc .

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