Created
August 13, 2012 03:47
-
-
Save andrewberls/3336825 to your computer and use it in GitHub Desktop.
Remove linked list node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static int | |
list_remove(node* root, node* n) { | |
node* temp = (node*) malloc(sizeof(node)); | |
temp = root; | |
node* garbage = (node*) malloc(sizeof(node)); | |
int found = -1; | |
while (temp) { | |
if (temp->next->val == n->val) { | |
garbage = temp->next; | |
/* If we're deleting the last item in the list, set the next pointer to NULL, | |
otherwise the node following the node to be deleted */ | |
temp->next = (garbage->next == NULL) ? NULL : garbage->next; | |
printf("setting temp next to %d\n", temp->next->val); | |
/* SEGFAULT HERE */ | |
free(garbage); | |
found = 0; | |
} else { | |
temp = temp->next; | |
} | |
} | |
return found; | |
} |
Also do yourself a favor and just run, clang file.c -o file -g
and run GDB wait for the segfault then run bt.
delete :: Eq a => a -> [a] -> [a]
delete n xs = filter (!= n) xs
I haven't done C++ in what feels like forever but if I'm not mistaken, your lines 3 and 4 are the funniest thing ever.
I can't edit... but line 5 too. Could you please explain to me why you are malloc'ing those pointers?
Also, as jroesch says, gdb should help you find the issue fairly quickly.
PS:
- Won't line 9 segfault if temp->next is NULL?
- I don't think your code checks the first node.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was about to actually test it out but I don't have any of the surrounding context, I'm pretty sure its the first 'if' statement. You are not checking the next for being null, before trying to access val.