Below, I wrote a primitive singly linked list in C. Function “addEditNode” MUST receive a pointer by value, which, I am guessing, means we can edit the data of the pointer but can not point it to something else. If I allocate memory using malloc in “addEditNode”, when the function returns, can I see the contents of first->next ? Second question is do I have to free first->next or is it only first that I should free? I am running into segmentation faults on Linux.
#include <stdio.h>
#include <stdlib.h>
typedef struct list_node list_node_t;
struct list_node
{
int value;
list_node_t *next;
};
void addEditNode(list_node_t *node)
{
node->value = 10;
node->next = (list_node_t*) malloc(sizeof(list_node_t));
node->next->value = 1;
node->next->next = NULL;
}
int main()
{
list_node_t *first = (list_node_t*) malloc(sizeof(list_node_t));
first->value = 1;
first->next = NULL;
addEditNode(first);
free(first);
return 0;
}
First, yes you can “see” the contents of
first->nextwhen the function returns.node->nextis a value in the struct pointed to bynode, which points to the same place asfirst. When passing thefirstpointer by value, only the pointer itself is copied, not the whole structure it points to. In other words,*firstinmainis exactly the same data as*nodeinaddEditNode(not a copy), it’s just that each function has a different pointer (one calledfirstand one callednode) that point to that one structure.Second, yes you must free
node->nextas well or you will have a leak. When you free a pointer to a structure, it does not recursively free pointers that are members of that structure.However, I don’t see anything in that code that is incorrect or that should cause a segmentation fault (a leak won’t cause a segfault).