xcode - C linked list: Segmentation fault on Windows, works on Mac -
i'm trying go through linked list in c.
a list item defined as
struct list_element { struct list_element *next; int value; };
the list head defined as
struct list_head { struct list_element *front; struct list_element *end; };
and i'm trying print items
void printlist(struct list_head* head) { if(head == null|| head->front == null) { printf("list empty \n"); return 0; } struct list_element* elm = head-> front; int numberofelements = 0; while(elm != null) { printf("%i", elm -> value); printf(" "); elm = elm -> next; } printf("\n"); }
this works perfect on mac in xcode , on https://ideone.com, on windows , http://codepad.org results in "segmentation fault". seems
while(elm != null) { printf("%i", elm -> value); printf(" "); elm = elm -> next; }
causes issues. seems elm doesn't point null last item, though should.
i'm adding items
struct list_element* list_push(struct list_head* head) { //list head null if(!head) { return null; } //initialize list element struct list_element* elm = malloc(sizeof(struct list_element)); if(elm == null) { //couldn't alloc memory return null; } if(head->front) { head->front = elm; head->end = elm; } else { //list head not null, set next elm point current elm elm -> next = head -> front; head->front = elm; } return elm; }
and i'm confused why same code work in places not in others. (it works on ideone , xcode, doesn't work on codepad , code::blocks on windows same code)
you have initialize ele->next
null
first element of list, otherwise access uninitialized memory in elm = elm->next
last element of list. apart have change if(head->front)
if ( head->front == null )
. adapt code this:
struct list_element* list_push(struct list_head* head) { if ( head == null ) return null; struct list_element* elm = malloc(sizeof(struct list_element)); if ( elm == null) return null; if ( head->front == null) // <-------------- { elm->next = null; // <--------------- head->front = elm; head->end = elm; } else { elm->next = head->front; head->front = elm; } return elm; }
make sure initialized head->front
head->end
null
.
Comments
Post a Comment