This is my function to add a new node using double pointer
void insertBefore(node_t **first)
{
node_t *new = NULL;
new = (node_t *) malloc(sizeof(node_t));
new->next = *first;
*first = new;
free(new);
}
If I use it once, everything seems to work fine. However, if I use it again, my linked-list is messed up. I have the output image below (same thing happened to my function to insert node to any position). I tried to put some very specific part of the code, so if you suspect that I must have been doing something wrong at other parts, please tell me. Any idea what did I do wrong?
node_tstructure will have more than one element; your code would normally have one or more other function parameters which would be used to initialize the other fields in the structure. At the least, you should normally make sure all the other fields are initialized to a known value (""or0orNULLare often good choices in the absence of any better value, but it depends on what else the structure contains and what it describes). I'll assume you just did a thorough job of creating an MCVE (minimal reproducible example).newas a variable name.