1

I tried to define a node struct which includes a node* next. I write an append(node* n) function to add a new node next to the previous one, but every time I run the code, it gives me seg fault. My code is following:

#include<stdlib.h> #include<stdio.h> typedef struct _log_t { struct _log_t* next; }log_t; void initi(log_t* l) { l = (log_t*)malloc(sizeof(log_t)); l -> next = NULL; } void append(log_t* l){ l->next = (log_t*)malloc(sizeof(log_t)); l->next->next = NULL; l = l->next; } 

Thanks in advance for any help!

2 Answers 2

6
 l = l->next; 

That line is not doing what you think it is - in fact, its doing nothing.

Perhaps you want to pass log_t* as a log_t**, or return the new log_t*.

Sign up to request clarification or add additional context in comments.

Comments

-2

You're dereference a pointer you never initialized. That's why it's crashing :)

// OK (but you should check for malloc() failing, too!) void initi(log_t* l) { l = (log_t*)malloc(sizeof(log_t)); l -> next = NULL; } void append(log_t* l){ // OK... l->next = (log_t*)malloc(sizeof(log_t)); // BAD!!!! l->next: allocated. l->next->next: *NOT* initialized! l->next->next = NULL; l = l->next; } 

Here's what I think you possibly mean:

log_t * append (log_t* l) { // Initialize the head if (l == NULL) { l = (log_t *)malloc(sizeof (log_t)); l->next = NULL; } // Initialize a sub-node else { l->next = (log_t *)malloc(sizeof (log_t)); l->next->next = NULL; } // Always return the head return l; } 

4 Comments

hi is just doing the initalization... perfectly fine. there is no dereferencing.
that update is even worse.. append(NULL).. that's just doesn't make any sense.
@yi_H: the point is you can't dereference "l->next->next" until you've both 1) allocated "l", and 2) initialized "l->next". It's perfectly appropriate to initialize l->next either to NULL, or to a newly allocated value. It's NOT OK to use it BEFORE you've initialized it.
you should take a rest, then re-read this thing, because you're talking nonsense. he allocated the memory in the previous line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.