Search code examples
cstructmalloctypedef

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 ?


Solution

  • 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.