baltasaurus
baltasaurus

Reputation: 11

Why isn't my linked list getting updated?

Using the debugger, the linked list seems to be successfully created inside the function, but it doesn't get updated "outside" in main. I don't know why it isn't updating since I'm using addresses and dynamic memory allocation, which if I'm not mistaken, doesn't get "cleared" once the function is exited.

int populate(node* list)
{
    node* temp = NULL;

    while(1)
    {
        printf("insert word: ");
        char* word = getstring();
        if(strcmp(word, "stop") == 0)
        {
            break;
        }
        
        //create a node
        node* n = malloc(sizeof(node));
        if(n == NULL)
        {
            return 1;
        }
        
        //put stuff in node
        n->word = word;
        n->next = NULL;
        
        if (list == NULL) //first case only
        {
            list = n;
            temp = n;
        }
        else
        {
            //set previous next to current node
            temp->next = n;
            
            //set pointer to current node
            temp = temp->next;
        }
        
    }
}

int main()
{
    node* list = NULL;
    
    while(1)
    {
        printf("insert command: ");
        char* word = getstring();
        
        if (strcmp(word, "stop") == 0)
        {
            break;
        }
        else if (strcmp(word, "add") == 0)
        {
            populate(list);
        }
        else if (strcmp(word, "read") == 0)
        {
            readList(list);
        }
    }
}

Also, after my code runs, is the memory I've allocated automatically freed? Or am I gobbling up small chunks of my computers memory every time I test my program. (I'm using Xcode)

Upvotes: 1

Views: 434

Answers (1)

Waqar
Waqar

Reputation: 9331

You need to pass the pointer node* list as a double pointer (pointer to pointer) instead of a pointer:

int populate(node** list)
{

This is because C language has value semantics. Everything is passed by value. So when you pass the list to populate(), you create a copy of the original pointer. They are both pointing to the same memory, but changes to one of the pointer will not be reflected in the other. This is why your list never gets updated.

Everything else will remain mostly the same. When calling the populate function you need to pass the address of the list:

populate(&list);

And in the populate() function, every occurrence of list will become *list since you need to de-reference it to get the original pointer.

Upvotes: 1

Related Questions