Search code examples
cmemory-leakslinked-listdynamic-memory-allocation

Dynamic memory allocation for node in linked list


Why when i have to declare a pointer to a node (head) I also have to allocate memory with malloc or calloc for it? I saw that the code that generate a list (not imported here) works well also without allocate memory for it and just declaring node *head.

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

int main(){

    node *head;

    head = (node*) malloc(sizeof(node));
    head = NULL;

And why when I allocate memory like above i have to write (node*)? Isn't it already allocated to a struct node since I'm doing it on head? What is the meaning of that line of code exactly? Moreover when I write head = NULL am I set the address of the pointer head to NULL or what?


Solution

  • This code snippet

    node *head;
    
    head = (node*) malloc(sizeof(node));
    head = NULL;
    

    produces a memory leak.

    At first a memory for an object of the type node was allocated and its address was assigned to the pointer head

    head = (node*) malloc(sizeof(node));
    

    and then at once the value of the pointer was overwritten.

    head = NULL;
    

    As a result the address of the allocated memory was lost and the allocated memory can not be freed.

    The code snippet does not make any sense. It will be enough to write

    node *head = NULL;
    

    In this case you will initially have an empty list.

    And why when I allocate memory like above i have to write (node*)?

    The function malloc returns a pointer of the type void *. A pointer of the type void * can be assigned to a pointer of any other object type. So in C the casting is redundant.

    In C++ you have explicitly to cast a pointer of the type void * to the type of the object pointer to which the pointer of the type void * is assigned.

    Moreover when I write head = NULL am I set the address of the pointer head to NULL or what?

    You did not set the address of the pointer itself. The pointer was allocated by the compiler and has the automatic storage duration. You set the value of the variable head that has the type node * to NULL.