I need to create a linked list in my program. In my program the list is allocated on the heap with malloc(), than i try to visit it but i get a segmetation fault;
EDIT: i get the SIGSEGV at this line “while(!(node->nodeType == TYPE_END_LIST)){“
struct dagNode *createList(int k);
struct dagNode *newNodeXInterval(int type, int val);
struct dagNode *createList(int k){
struct dagNode *head, *node;
printf("\nList %d = ", k);
head = newNodeXInterval(TYPE_EDGE_OR_GAP, getVal(k,1));
node = head;
int i;
for (i=1; i<LENGTH_OF(k); i++){
node->next = newNodeXInterval(TYPE_XTEST, getRightPointOf(k,i));
node = node->next;
node->next = newNodeXInterval(TYPE_EDGE_OR_GAP, getVal(k,i+1));
node = node->next;
}
node = newNodeXInterval(TYPE_END_LIST, 0);
node = head; // i think that here there is the error
printf("%d", node->val); i=0;
while(!(node->nodeType == TYPE_END_LIST)){
printf("%d ", i);
node = node->next;}
return head;}
struct dagNode *newNodeXInterval(int type, int val){
struct dagNode *node = (struct dagNode *) malloc(sizeof(struct dagNode));
if (type == TYPE_EDGE_OR_GAP){
*node = (struct dagNode) {(val<0)? TYPE_GAP:TYPE_EDGE, val, NULL, NULL, NULL};
}
else{
*node = (struct dagNode) {type, val, NULL, NULL, NULL};
}
return node; }
The caller function would get the head of the list.
As far as I can tell, the problem is with the line
Before the assignement,
nodepoints to the last node in your linked list, and the previous node has itsnextpointer equal tonode. After the assignement,nodepoints to the newly created node with typeTYPE_END_LIST, but the previous node has itsnextpointer unchanged (i.e. it still holds the original value ofnode). In other words, your newly created node is not a part of the list, and thus the conditionnode->nodeType == TYPE_END_LISTin the followingwhile()loop will never evaluate to true, and you’ll end up dereferencing a null pointer when you go past the end of the list. Changing the line toshould fix the problem.