Home > Mobile >  Does malloc(sizeof(x)) initialise the allocated memory with x?
Does malloc(sizeof(x)) initialise the allocated memory with x?

Time:06-14

Does tmp = malloc(sizeof(x)); the same automatically as tmp = malloc(sizeof(x)); *tmp = x;?

More specifically, is malloc instantly initialising my variable or is it just allocating memory and I have to initialise it myself?

CodePudding user response:

No.

The memory returned by malloc isn't initialized.

Quoting cppreference,

Allocates size bytes of uninitialized storage.

CodePudding user response:

No. Even if malloc weren't defined to be uninitialized storage, sizeof(x) has nothing to do with the runtime value of x (it's just a friendly way to find the size of a variable's underlying type). There's no runtime use of the value of x at all in the code you provided.

CodePudding user response:

The operator sizeof yields the size in bytes of its operand.

That is for example if the identifier x denotes a name of a variable of the type int then the expression sizeof( x ) yields the value 4 provided that for objects of the type int the compiler reserves 4 bytes.

So this call

tmp = malloc(sizeof(x));

will be equivalent to the call

tmp = malloc(sizeof(int));

that in turn is equivalent to

tmp = malloc( 4 );

This statement just tries to allocate dynamically 4 bytes. The allocated memory is uninitialized.

Moreover the expression sizeof( x ) if x is not a variable length array is evaluated at compile time before the program begins its execution.

You could initialize it with zeroes the following way

tmp = calloc( 1, sizeof( x ) );

CodePudding user response:

No, the function malloc() simply allocates memory on the heap. It doesn't initialize the pointer.

  • Related