Tom
Tom

Reputation: 71

How to initialize all the pointer fields of struct pointer to NULL?

I have the following struct:

 struct node {
    int data;
    struct node *next;
};


struct node *n1 = malloc(sizeof(struct node));

I am not sure how initialize all the pointer fields of struct pointer to NULL without causing any potential for memory leaks?

Upvotes: 7

Views: 11972

Answers (2)

paulsm4
paulsm4

Reputation: 121629

You have four choices:

1) Set the pointers manually, e.g. node-> next = NULL;

2) Use calloc() to zero out the memory when you allocate it

3) Use memset() to zero out the memory after you've allocated it.

... OR ...

4) Don't worry about explicit initialization until you actually need to use the struct. Design your program such that you make sure any pointer is assigned before you try to read it.

FYI, this is one of the main purposes of a "constructor" in OO languages like C++ or C#: to initialize "class invariants".

PS:

5) I forgot about C99 struct initialization, which Leushenko mentioned:

what is the difference between struct {0} and memset 0

struct A
{
    int x;
    int y;
};
...
A a = {0};

This is vastly preferred to either calloc() or memset().

It also applies to other initialization values besides "0":

C99 Standard 6.7.8.21

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Upvotes: 3

chqrlie
chqrlie

Reputation: 144695

You need to initialize the members of the structure after you allocate it with malloc:

struct node {
    int data;
    struct node *next;
};

struct node *n1 = malloc(sizeof(struct node));
n1->data = 0;
n1->next = NULL;

If you want to initialize your structure in one step with default values, which can be handy if it is much larger, use a static structure with these defaut values:

struct node def_node = { 0, NULL };

struct node *n1 = malloc(sizeof(struct node));
*n1 = def_node;

Alternately, you can use the C99 syntax:

struct node *n1 = malloc(sizeof(struct node));
*n1 = (struct node){ 0, NULL };

As commented by Leushenko, you can shorten the initializer to { 0 } for any structure to initialize all members to the appropriate zero for their type:

struct node *n1 = malloc(sizeof(struct node));
*n1 = (struct node){ 0 };

Upvotes: 7

Related Questions