I'm trying to code a Linked List in C. I know this is very simple, but I'm doing this as an exercise to learn pointers in C. I'm following this video, specifically at 8:05 where he creates this printlist() function and passes through the head of the list. I'm trying to do the same thing:
My code is below:
#include <stdio.h>
typedef struct node_t{
int value;
struct node_t *next;
}node_t;
void print_ll(node_t *head) {
node_t *tmp = head;
printf("first node val: %d and next pointer %p\n", tmp->value, tmp->next); //prints 5 and some non-NULL address.
/*
while (tmp != NULL) {
printf("%d - ", tmp->value);
tmp = tmp->next;
}
*/
printf("\n");
}
node_t *init_ll(int value) {
node_t new_node;
new_node.value = value;
new_node.next = NULL;
node_t *head = &new_node;
return head;
}
int main() {
node_t *head = init_ll(5);
printf("n1.value = %d\n", head->value); //prints 5
printf("n1.next ptr = %p\n", head->next); //prints NULL
print_ll(head);
return 0;
}
In my print_ll function, I pass the head of the Linked List, and I was trying to use that while loop to walk through the linked list, but I noticed that tmp->next isn't NULL like it's declared in my init_ll() func. I believe I will have to do this by passing a pointer to the head.. But my question is why this guy's code works (in the video), which logically makes sense to me, but mine doesn't.
CodePudding user response:
Your problem lies in te init_ll
function, because you never allocate memory for the new node, instead, you use the local memory space of the function (the stack). Therefore, when you assign the address of new_node
to your head
"pointer", you're effectively returning the address of the stack space of your function.
In other words, the .next
doesn't work because, even though you've set it, after the function return, the stack space is free to be used again by any other functions, and therefore, anything can be written in the memory you're referencing (this is undefined behavior).
So, your function looks like this:
node_t *init_ll(int value) {
node_t new_node;
new_node.value = value;
new_node.next = NULL;
node_t *head = &new_node;
return head;
}
And it should use memory allocation with malloc(3)
(and free(3)
when no longer in use).
node_t *init_ll(int value) {
node_t *new_node;
/* memory allocation failed */
if(!(new_node = malloc(sizeof *new_node))) return NULL;
/* now we have to change . to ->
* because we're using pointers
*/
new_node->value = value;
new_node->next = NULL;
return new_node;
}
CodePudding user response:
You have not allocated memory on heap. Local memory always resides on stack which is the reason why your program is not working.
node_t *init_ll(int value) {
node_t *new_node;
/* memory allocation on heap */
new_node = (node_t *)malloc(sizeof(node_t));
if (!new_node) return NULL;
new_node->value = value;
new_node->next = NULL;
return new_node;
}