How to initialize all fields of a pointer to a structure pointer to NULL?

I have the following structure:

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


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

I'm not sure how to initialize all fields of a pointer to a structure pointer to NULL without creating any potential for memory leaks?

+4
source share
2 answers

You need to initialize the elements of the structure after selecting 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 convenient 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;

Alternatively, you can use the C99 syntax:

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

, { 0 } , :

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

:

1) , . node-> next = NULL;

2) calloc(),

3) memset(), , .

... ...

4) , . , , , .

FYI, "" OO, ++ #: " " .

PS:

5) C99, :

struct {0} memset 0

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

calloc(), memset().

, "0":

C99 6.7.8.21

, , , , , , , , .

+3

Source: https://habr.com/ru/post/1625587/


All Articles