de3z1e
de3z1e

Reputation: 441

Setting all struct pointer members to NULL

If I set a pointer to a struct to point to a block of memory via malloc, will all the members initialize to their respective default values? Such as int's to 0 and pointer's to NULL? I'm seeing that they do based on this sample code I wrote, so I just wanted someone to please confirm my understanding. Thanks for the input.

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>

typedef struct node
{
    bool value;
    struct node* next[5];
}
node;

int main(void)
{
    node* tNode = malloc(sizeof(node));

    printf("value = %i\n", tNode->value);

    for (int i = 0; i < 5; i++)
    {
        if (tNode->next[i] == NULL)
            printf("next[%i] = %p\n", i, tNode->next[i]);
    }
}

Upvotes: 2

Views: 1031

Answers (3)

sumithdev
sumithdev

Reputation: 331

malloc() function never initializes the memory region. You have to use calloc() to specifically initialize a memory region to zeros. The reason you see initialized memory is explained here.

Upvotes: 7

rabi shaw
rabi shaw

Reputation: 441

You can use static const keywords to set the member variables of your struct.

#include

struct rabi 
{
int i;
float f;
char c;
int *p; 
};
int main ( void )
{

static const struct rabi enpty_struct;
struct rabi shaw = enpty_struct, shankar = enpty_struct;


printf ( "\n i = %d", shaw.i );
printf ( "\n f = %f", shaw.f );
printf ( "\n c = %d", shaw.c );
printf ( "\n p = %d",(shaw.p) );


printf ( "\n i = %d", shankar.i );
printf ( "\n f = %f", shankar.f );
printf ( "\n c = %d", shankar.c );
printf ( "\n p = %d",(shankar.p) );
return ( 0 );
}



Output:

 i = 0
 f = 0.000000
 c = 0
 p = 0

 i = 0
 f = 0.000000
 c = 0
 p = 0

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 224864

No. malloc never initializes the allocated memory. From the man page:

The memory is not initialized.

From the C standard, 7.20.3.3 The malloc function:

The malloc function allocates space for an object ... whose value is indeterminate.

Upvotes: 4

Related Questions