Search code examples
cdata-structureslinked-liststackmalloc

allocating node on the heap, difference between first assign to NULL and direct assignment with malloc [c]


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

Solution

  • 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.