Question

My problem is that, when i try to add a node to my singly linked list for the first time, everything goes expected, but when i want to add another node, my program crashes. Seems like my error is caused by trying to write to 0 address. however i can't seem to find the error in my code. am i using malloc right ? Here is the code :

typedef struct linkedList
{
    int StudentId;
    char name[100];
    char dep[100];
    struct linkedList *next;
} LinkedList;

LinkedList *head = NULL;
LinkedList *current = NULL;

LinkedList *createList(int val, char name[], char dep[])
{
    LinkedList *ptr = (LinkedList *)malloc(sizeof(LinkedList));
    if (ptr == NULL)
    {
        printf("Node Creation Failed\n");
        return NULL;
    }
    ptr ->StudentId = val;
    strcpy(ptr -> name, name);
    strcpy(ptr ->dep, dep);
    ptr ->next = NULL;
    head = current = ptr;
    return ptr;
}

LinkedList *addToList (int val, char name[], char dep[])
{
    if (head == NULL)
    {
        return (createList(val, name, dep));
    }
    else
    {
        LinkedList *ptr = (LinkedList *)malloc(sizeof(LinkedList));
        if (ptr = NULL)
        {
            printf("Node Creation Failed\n");
            return NULL;
        }
        ptr -> StudentId = val;
        strcpy(ptr ->name, name);
        strcpy(ptr ->dep, dep);
        ptr -> next = NULL;
        current -> next = ptr;
        current = ptr;
        return ptr;
}

}

in main function: AddtoList(10,"abc","abc"); calls createList, no problem but If i use AddtoList again, program crashes, createList and AddtoList are really similar to each other, can't figure out what the problem is.

Was it helpful?

Solution

Change

if (ptr = NULL)

to

if (ptr == NULL)

In your case, ptr is assigned to NULL and expression within if is evaluated to 0. Control goes to ptr -> StudentId = val;. It tries to access write protected memory, hence the crash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top