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
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*.
answered Feb 21, 2012 at 23:48
Yann Ramin
33.2k3 gold badges63 silver badges83 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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;
}
answered Feb 21, 2012 at 23:50
paulsm4
123k23 gold badges175 silver badges245 bronze badges
4 Comments
Karoly Horvath
hi is just doing the initalization... perfectly fine. there is no dereferencing.
Karoly Horvath
that update is even worse.. append(NULL).. that's just doesn't make any sense.
paulsm4
@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.
Karoly Horvath
you should take a rest, then re-read this thing, because you're talking nonsense. he allocated the memory in the previous line.
lang-c