I'm probably missing something really important regarding pointers and memory management.
I'm building a doubly linked list. I have a struct Node:
struct Node {
void* data;
nodep prev;
nodep next;
};
with nodep being a typedef for a pointer to such a Node:
typedef struct Node * nodep;
Now I wrote an insertAt() function, which takes a nodep lst which is basically a pointer to the first element in the list, or NULL for the empty list, an int pos, the position at which to insert the element and a void* data, which is the payload of the Node. This is the excerpt my code, where I get an error:
nodep insertAt(nodep lst, int pos, void *data){
nodep new = malloc(sizeof(struct Node));
[...]
new -> data = data;
assert(new != NULL);
printf("memory allocated!\n");
/* insert at last position */
if(pos == -1) {
[...]
/* insert at first position */
} else if (pos == 0) {
if(lst == NULL) {
new -> next = lst;
lst = new;
} else {
[...]
}
/* insert at pos */
} else {
[...]
}
return new;
}
This is how I call insertAt() in my main() function:
int i;
nodep lst = NULL;
insertAt(lst, 0, "test");
When I run my program with valgrind, I get an
Access not within mapped region at adress 0x10
for this line of code:
lst = new;
What I want to do is make the nodep lst point to the nodep new, which then is the first element of the list. I don't really get, why I encounter this error.
Thanks in advance for any help.
Cheers Nick