Shen
Shen

Reputation: 3169

pointer malloc fail

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!

Upvotes: 1

Views: 192

Answers (2)

paulsm4
paulsm4

Reputation: 121649

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;
}

Upvotes: -2

Yann Ramin
Yann Ramin

Reputation: 33177

 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*.

Upvotes: 6

Related Questions