0

Seemingly simple C code is seemingly not allowing me to remove the first element from a linked list. I can, however, successfully remove any other individual element and can successfully delete the whole linked list.

typedef struct list{
    int data;
    struct list * next; 
} list;

void remove_element(list * node, unsigned int index){
    if (node == NULL)
        exit(-1);

    list *currElem = node;

    if (index == 0) {
        node = node->next;
        currElem->next = NULL;
        free(currElem);
        return;
    }

Produces the follwing: "free(): invalid pointer: 0xbfabb964"

I've followed the same format for all of my other manipulation functions with no issues. Similar threads on forums don't seem to be dealing with this particular problem.

sxt643
  • 45
  • 4
  • 1
    Setting `node = node->next` accomplishes nothing since all that does is change the local copy of `node`. See for example, [this question](https://stackoverflow.com/questions/5531765/change-pointer-passed-by-value) or [this question](https://stackoverflow.com/questions/22918628/linked-list-not-working-for-insertion). – user3386109 Oct 18 '19 at 00:29
  • 1
    agree if you want to modify the pointer in the calling function, you have to manipulate a pointer to pointer (list ** node) you don't provide then calling code to remove_element, maybe you'll find a mistake there. – nobur Oct 18 '19 at 00:39

1 Answers1

0

You can read the explanation in this pdf on the Push function which explains it: http://cslibrary.stanford.edu/103/

This is where c gets funky pschologically. You instinctively want to label a pointer as a pointer, which it is. But it is a pointer value, not a pointer reference. It's like the holy spirit of the C divinty. The triumvirate. C passed arguments to functions by value, not by address/reference. So, what do you do to pass a variable by reference? Remember, the solution is so obvious, it really didn't make sense to me for a week, I swear to god.