Home > Blockchain >  allocating node on the heap, difference between first assign to NULL and direct assignment with mall
allocating node on the heap, difference between first assign to NULL and direct assignment with mall

Time:01-27

I am trying to implement a stack using linked list, and firstly I have the following code:

typedef struct Node {
    int data;               // integer data
    struct Node* next;      // pointer to the next node
} Node;


Node* inti_stack() {
    Node* node = NULL;// allocate a new node in a heap
    node = malloc(sizeof * node);
    if (!node) exit(EXIT_FAILURE);
    return node;
}

For the inti_stack function, can I just do the following and that would be equivalent?

Node* inti_stack() {
    Node* node = malloc(sizeof * node);
    if (!node) exit(EXIT_FAILURE);
    return node;
}

CodePudding user response:

In the first case:

Node* node = NULL;// allocate a new node in a heap
node = malloc(sizeof * node);

The value of node is determinate. malloc() will overwrite it with a pointer to a chunk of heap memory if it succeeded.

In the second case:

Node* node = malloc(sizeof * node);

The value of node is indeterminate, but it's going to be overwritten by malloc() nevertheless.

So yes, they're both equivalent. Though the latter is preferred.

NB that malloc() will return a NULL pointer on failure, and set errno on some implementations. Your code should check for it.

Aside: Why exit() without an error message?

if (!node) exit(EXIT_FAILURE);
/* I'd expect a fprintf()/perror() here */

CodePudding user response:

In the first code snippet

Node* node = NULL;// allocate a new node in a heap
node = malloc(sizeof * node);

the declared pointer node is at once overwritten.

So it is enough to write

Node* node = malloc(sizeof * node);

If the function malloc is unable to allocate memory it returns a null pointer.

Pay attention to that the name of the function inti_stack is unclear.

  • Related