Thursday, 15 September 2011

c - Segmentation Fault 11 when trying to create new linked list from sorted list -



c - Segmentation Fault 11 when trying to create new linked list from sorted list -

just explain going on, inputting sorted linked list method. in linked list nodes contain strings. nodes contain string, , 2 counters mentioned later. these strings alphanumerical , can repeat. in end, want output linked list in each node contains unique word (all lowercased), counter number of occurrences, , counter different variances of word (variances caused different capitalizations of characters). believe works logically; however, segmentation fault.

thanks in advance!

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> typedef int bool; #define true 1 #define false 0 struct node{ char value[100]; int numoccur; int numvariance; struct node *next; }; struct node * getfinalnodes(struct node *head){ struct node * curr; struct node * finalnode; struct node * ptr; struct node * finalcurr; struct node * prev; int m = 0; int z = 0; char lowercase1[100]; char lowercase2[100]; curr = head; //curr = head of sorted node finalnode = head; ptr = finalnode; finalcurr = finalnode; for(m = 0; curr->value[m] != '\0'; m++){ finalnode->value[m] = tolower(curr->value[m]); //gets first word lower-cased } ptr->numoccur=1; //occurance 1 ptr->numvariance=1; //variance 1 while(curr != null && curr->next != null){ prev = curr; curr = curr->next; if((strcmp(prev->value, curr->value) != 0) && (strlen(prev->value) == strlen(curr->value))){ //example: ab vs. ab for(z=0; curr->value[z] != '\0'; z++){ //turn prev , curr lowercase lowercase1[z] = tolower(prev->value[z]); //ex. ab->ab , ab->ab lowercase2[z] = tolower(curr->value[z]); } if(strcmp(lowercase1,lowercase2) == 0){ //if values same, means same words, different capitalizations ptr->numoccur++; ptr->numvariance++; } else{ //if values different, different strings , set curr.value new finalnode strcpy(finalnode->value,lowercase2); ptr->next = finalnode; ptr = ptr->next; ptr->numoccur = 1; ptr->numvariance =1; } } else if((strcmp(prev->value, curr->value) != 0) && (strlen(curr->value) != strlen(prev->value))){ //created arrays prev , curr for(z=0; curr->value[z] != '\0'; z++){ //turn prev , curr lowercase //ex. ab->ab , ab->ab lowercase2[z] = tolower(curr->value[z]); } strcpy(finalnode->value,lowercase2); ptr->next = finalnode; ptr = ptr->next; ptr->numoccur = 1; ptr->numvariance =1; } else if(strcmp(prev->value, curr->value) == 0){ ptr->numoccur++; } } };

in loop

while(curr != null){ prev = curr; curr = curr->next; if((strcmp(prev->value, curr->value) != 0) && (strlen(prev->value) == strlen(curr->value))){

curr null @ end after curr = curr->next;.

then strcmp(prev->value, curr->value) dereferences null pointer.

you alter loop status to

while(curr != null && curr->next != null)

c arrays linked-list segmentation-fault nodes

No comments:

Post a Comment