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 20:12

>>7

>Now cut it down to one, which is all that's really needed.

I don't see much of a reason to, honestly.

>As for your crash, you're probably trying to free statically or stack-allocated memory or something equally retarded.

That's not it, because I free that same memory later in the program without issue.

// Free the linked list
searcher = head;
while(searcher != NULL)
{
    searcher = searcher->next;
    free(head);
    head = searcher;
}

This is the same linked list of the same structs. Any members of the linked list that I didn't use the 'remove' function on would get freed by this bit of code, and this bit of code has never given me errors at all. This bit of code is at the very end of 'main'.

Aside from one 'free' statement being in a function that gets passed the head pointer and the other 'free' statement being at the end of main, I can't find much of a difference between the two, let alone enough of a difference that one would cause an exception error and the other wouldn't.

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