Originally Posted by
jimtuv
The problem would be if the node to delete were at the beginning removing the node isn't the problem because the following node already has the pointer pointing to the correct node. It's the Head or list pointer that would have to be fixed as it would need to point to the second node not the first.
seems like you could do this recursively. By setting up the deletion function to return the pointer of the node. Just a thought maybe I am way off.
This is where pointers get slightly complicated. I'm not sure what you mean by "do this recursively", but with the delete you have two choices and you seem to have the first one:
1) Always return the head node in case it has changed (because the head was deleted). Here assume the node is identified using a char string, "val":
Code:
node *delete(node *head, char *val); // function prototype
/* usage */
head = delete(head, "this one");
2) The other option is to pass in the address of the pointer which points to head:
Code:
void delete(node **head, char *val); // function prototype
/* usage */
delete(&head, "this one");
This is called a "pointer to a pointer" and that's another important concept . It allows you to reassign head without using the return value -- so the return value could be reserved for something else, say an error code. Beyond that it's just a matter of style, but you should know how to do both for cases when you cannot use the return value in this way.
Originally Posted by
Elysia
Keep in mind that when using malloc, you introduce memory allocation bugs.
Memory bugs are usually of this form:
Code:
char *ptr;
while (some loop) {
ptr = malloc(123);
[do something with pointer]
}
Since ptr was not freed or assigned to anything else in the loop, the memory to which it pointed (different memory for each iteration!) is still reserved for the duration of the program, but you now have no handle (pointer) to that memory, meaning you cannnot access or use it, or free it. This is called a memory leak.
So in general "memory bugs" are pretty simple and easy to prevent. The only thing which makes them more potentially troublesome than something which causes a crash or bad output is that you can fail to notice them. However, use of a simple memory profiler such as valgrind (on linux) can solve that problem.