Search code examples
cdata-structuresstructlinked-listdynamic-memory-allocation

Simple link list program in C


Simple code of Link List implementation in C . Is it correct way to write or I am missing anything ? Is free section is ok?

typedef struct box{// data type definition 
        int data;
        struct box* next;
    } node; // "node"

node* node1 = (node *)malloc( sizeof(node));// heap memory allocation for node1
    if(node1 != NULL){ // ( safety check)
        node1->data = 1;//assign value
        node1->next = NULL;// doesn't point to anyone
    }

node* node2 =(node*)malloc(sizeof(node));// node 2 work
    if(node2 != NULL) {
        node2 ->data = 2;
        node2->next = NULL;
    }

node1->next = node2;//first connection
node2->next = NULL;//second connection

for(node *tmp =node1; tmp !=NULL; tmp=tmp->next){// printing value in nodes using *tmp pointer
        printf("%i\n",tmp->data );
    }

free(node1);//delete node1 allocation on heap
free(node2);//delete node 2 allocation on heap

Solution

  • In this declaration

    struct box{// data type definition 
        int data;
        struct box* next;
    } node; // "node"
    

    you declared the variable node of the type struct box that is not further used.

    It seems you mean a typedef declaration like

    typedef struct box{// data type definition 
        int data;
        struct box* next;
    } node; // "node"
    

    As a result these statements

    node* node1 = (node *)malloc( sizeof(node));
    node* node2 =(node*)malloc(sizeof(node));
    

    shall produce compilation errors.

    If your list is supposed to contain for example 100 nodes will you declare 100 variables node1 ,..., node100?

    You need to write a separate function that includes new nodes in the list.

    These statements

    node1->next = node2;//first connection
    node2->next = NULL;//second connection
    

    can invoke undefined behavior if either pointer is equal to NULL.