Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

I swear I'm used to C you guys

Name: Anonymous 2013-05-29 16:37

So, in my code, I have the following function to remove nodes from a linked list.

colBox* remove(colBox* head, colBox* target)
{
    // If the target is the head of the linked list, free the head and return the rest of the list (whatever 'head' was pointing to)
    if(head == target)
    {
        target = target->next;
        free(head);
        return target;
    }
   
    // If the target is immediately following the head of the linked list, set head's "next" to whatever came after that target and free 'target'
    if(head->next == target)
    {
        head->next = head->next->next;
        free(target);
        return head;
    }

    // Otherwise, there's enough room in the linked list to search through it properly, find the target, and remove it
    colBox* searcher = head;
    while(searcher->next != target)
    {
        searcher = searcher->next;
    }
    searcher->next = target->next;
    free(target);
    return head;
}

However, I'm always getting "Access violation reading location 0xfeeefeee" exception errors during the lines that say 'free'. If I comment those lines out, the code appears to work exactly as I intended it, but I know that there's memory not being properly freed. The code I have at the end of the program in 'main', to free whatever remains of the linked list, doesn't cause any errors. Can anyone tell me why errors are happening here? I'm pretty sure there aren't any rules about 'free' lines needing to be in 'main'.

Name: Anonymous 2013-05-29 18:51

>>4

Good point.

There's one situation when dealing with linked lists where you need three branches, but I couldn't remember which one it was. I guess it might have been something to do with BSTs instead that needed three branches? Regardless,

colBox* remove(colBox* head, colBox* target)
{
    // If the target is the head of the linked list, free the head and return the rest of the list (whatever 'head' was pointing to)
    if(head == target)
    {
        target = target->next;
        //free(head);
        return target;
    }

    // Otherwise, there's enough room in the linked list to search through it properly, find the target, and remove it
    colBox* searcher = head;
    while(searcher->next != target)
    {
        searcher = searcher->next;
    }
    searcher->next = target->next;
    //free(target);
    return head;
}

As soon as I uncomment the 'free' lines, I get exceptions whenever the code reaches those 'free' lines.

>>5

That seems wholly unrelated.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List