L
Lars
Hi all
If this is the wrong list for beginners trouble I apologize.
please refer to me the correct list in such case.
I am trying to create a simple linked list but I keep getting segmentation
errors and I dont know why. I realize that I do not free the allocated
memory but the segfault happpens (it seems) with the insert function.
Can any one explain ?
Regards Lars
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
 struct node * next;
 int data;
} Node;
Node * alloc_node(int n);
void insert(Node * head, int n);
int main(){
 Node * nod = NULL;
 insert(nod,4);
 printf("%d\n",nod->data);
 printf("%10p\n", nod);
 printf("%10p\n", nod->next);
 return 0;
}
Node * alloc_node(int n){
 Node * tmp;
 tmp = (Node *) malloc(sizeof(Node));
 tmp->data = n;
 tmp->next = NULL;
 return tmp;
}
void insert(Node * head, int n) {
 Node * tmp;
 if (head==NULL) {
  head = alloc_node(n);
 }
 else { Â
  tmp = alloc_node(n);
  head->next = tmp;
 }
}
If this is the wrong list for beginners trouble I apologize.
please refer to me the correct list in such case.
I am trying to create a simple linked list but I keep getting segmentation
errors and I dont know why. I realize that I do not free the allocated
memory but the segfault happpens (it seems) with the insert function.
Can any one explain ?
Regards Lars
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
 struct node * next;
 int data;
} Node;
Node * alloc_node(int n);
void insert(Node * head, int n);
int main(){
 Node * nod = NULL;
 insert(nod,4);
 printf("%d\n",nod->data);
 printf("%10p\n", nod);
 printf("%10p\n", nod->next);
 return 0;
}
Node * alloc_node(int n){
 Node * tmp;
 tmp = (Node *) malloc(sizeof(Node));
 tmp->data = n;
 tmp->next = NULL;
 return tmp;
}
void insert(Node * head, int n) {
 Node * tmp;
 if (head==NULL) {
  head = alloc_node(n);
 }
 else { Â
  tmp = alloc_node(n);
  head->next = tmp;
 }
}