So, I tried doing something like this :
void place(struct node * list, int elem){
struct node *tmp = list;
struct node *prev ;
while(tmp && tmp->info <= elem){
prev = tmp;
tmp = tmp->next;
}
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = elem;
new->next = prev->next;
prev->next = new;
}
And it gave me a segmentation fault. gdb didn't help - showed a backtrace full of 000000 and ??.
But when I tried this :
void place(struct node * list, int elem){
struct node *tmp = list;
struct node *prev = tmp;
while(tmp && tmp->info <= elem){
prev = tmp;
tmp = tmp->next;
}
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = elem;
new->next = prev->next;
prev->next = new;
}
It worked fine ! The only difference between the two is that I'm initializing the local variable pointer prev in the second case, while I'm not doing so in the first case. But I can't see why the first case should be a segmentation fault ?
Can someone please explain this ?
Thanks!