ultrainstinct
ultrainstinct

Reputation: 255

Linkedlist in C

I am trying to create a linkedlist in C with pointers to structs at the moment. I am having some issues with my logic. So I was wondering, when removing the head of the list, would I return the removed item, OR, would I return the new head of the list. Also if I would return the new head, how would I free the memory? (This part is for an assignment) According to the assignment information, we are not supposed to free the removed item in the function. So yea, my question is, where would I free the memory? Here is that snippet of code. My code here just returns the new head, or returns NULL if the list is empty.

MusicRec * removeFromFront(MusicRec * theList)
{
    if(theList == NULL)
    {
        return NULL;
    } 
    return theList->next;
}

Upvotes: 0

Views: 199

Answers (3)

Deduplicator
Deduplicator

Reputation: 45704

Simple. Every allocation function has a companion deallocation function, and sometimes a whole suite of additional utility functions. Look in the docs for your allocator.

Deallocate just before you return. That might mean you need a temporary copy.

BTW: You are returning the proper value...

Upvotes: 1

avmohan
avmohan

Reputation: 2000

MusicRec *removeFromFront(MusicRec  **theListref)
{
    if(*theListref == NULL)
        return NULL;    // shouldn't there be an underflow error?
    Musicref *oldhead = *theListref;
    *theListref = *theListref->next;
    return oldhead;
}

I'm returning the pointer to old head. This can be freed in the calling function. The parameter is a reference to the current head pointer.

EDIT If I have to stick to your interface, your code is perfectly all right & I'll clean up memory in the calling function:

theListCopy = theList;
theList = removeFromFront(theList);
//free the ListCopy here

Upvotes: 1

Robert Groves
Robert Groves

Reputation: 7748

The function should save a pointer to the node being removed (the current head node), reset the head of the list to the next node (i.e. the current 2nd node) and then return the saved pointer to the removed node.

The user using your linked list api may have some complex structure being used as the node and in that case it is best left up to the caller to handle the memory cleanup of the data.

Upvotes: 1

Related Questions