Search code examples
cc89ansi-c

A function adding data to a linked list is enteting an infinite loop, only sometimes


First of all, here is my code, This is my linked list

        typedef struct data
    {
    
        struct data *next;
        int value : 24;
    
    }dataTable;

this is my function:

    void addData (int data){
    dataTable *dataPointer = NULL;
    if (dataTableHead == NULL){ /**create the head of the list if it doesn't exist*/
    
    dataTableHead = (dataTable *)malloc(sizeof(dataTable));
    dataPointer = dataTableHead;
    
    }

    else{/**if a data table exist (head exists)*/
        
        dataPointer = dataTableHead;
        
        while (dataPointer->next != NULL){/**gets the last link of the list*/
            dataPointer = dataPointer->next; 
        }

        dataPointer->next = (dataTable *)malloc(sizeof(dataTable));/**add a new symbol to the list*/
        dataPointer = dataPointer->next;
    }
    dataPointer->value = data;

}

so what happens is that I have in other .c files, fuctions that load text files and I read their lines and whenever I see something specific, I put it in the linked list.

it works perfectly for 1 file, no matter what I do to it (or at least for what I tried), but whenever I try 2 specific files, the 2nd file gets an infinite loop in this function in the while that is in the else statment.

I know I didn't send all of the code that I have, but my question is only regading this function, because I tried to figure it out for quite some time and I don't understand how it can even make infinite loop. because, datapointer will always be the head of the list, and this is the only function I used to store data in the linked list, and as far as I can see, it does not create any infinite loop of pointers. what did I do wrong that could cause this function to infinite loop?

and yes, I confirmed 100% that the loop is coming from the addData function


Solution

  • Using values of buffer allocated via malloc and not initialized invokes undefined behavior. You should initialize dataPointer->next.

        }
        dataPointer->next = NULL; /* add this line */
        dataPointer->value = data;
    
    }