Skip to content

Instantly share code, notes, and snippets.

@andrewberls
Created August 13, 2012 03:47
Show Gist options
  • Save andrewberls/3336825 to your computer and use it in GitHub Desktop.
Save andrewberls/3336825 to your computer and use it in GitHub Desktop.
Remove linked list node
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;
}
@jroesch
Copy link

jroesch commented Aug 13, 2012

Also do yourself a favor and just run, clang file.c -o file -g and run GDB wait for the segfault then run bt.

@jroesch
Copy link

jroesch commented Aug 13, 2012

 delete :: Eq a => a -> [a] -> [a]
 delete n xs = filter (!= n) xs

@tjk
Copy link

tjk commented Aug 13, 2012

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.

@tjk
Copy link

tjk commented Aug 13, 2012

I can't edit... but line 5 too. Could you please explain to me why you are malloc'ing those pointers?

@tjk
Copy link

tjk commented Aug 13, 2012

Also, as jroesch says, gdb should help you find the issue fairly quickly.

@tjk
Copy link

tjk commented Aug 13, 2012

PS:

  1. Won't line 9 segfault if temp->next is NULL?
  2. 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