user14857007
user14857007

Reputation:

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

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?

Upvotes: 1

Views: 150

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

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 ) );

Upvotes: 2

JakobS.
JakobS.

Reputation: 128

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

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155458

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.

Upvotes: 4

ikegami
ikegami

Reputation: 385966

No.

The memory returned by malloc isn't initialized.

Quoting cppreference,

Allocates size bytes of uninitialized storage.

Upvotes: 4

Related Questions