I'm developing a function in C that sorts text around a given key. Let's say you have the following file:
this line is first
but this line is second
finally there is this line
If you run the program and give it this file as input, it should print:
but this line is second
finally there is this line
this line is first
because but is alphabetically before finally is before this .
If, however, you pass in a flag to sort a different key, you'll get a different output. For example, if you call fastsort -2 on this file, you should get:
this line is first
finally there is this line
but this line is second
because line comes before there comes before this . Yes, I am assuming -2 means the second word in each line (like most people would, except computer scientists who always want to start at 0).
Moreover, if the specified key does not exist on a particular line of the input file, I should just use the last word of that line as the key. For example, if the user wants to sort on the 4th word ( -4 ), and the sort encounters a line like this ( sample line ), the sort should use the word line to sort that line.
My problem comes from this last assumption, I'm using strtok() to extract the word given by the key but I get a segmentation fault if the key is bigger than the number of words in the line. Here is the body of the function;
typedef struct {
char word[128];
int index;
} wordIndex;
char** fastsort(char** text, int word){
char** sortedText;
char* LineAux;
int i;
wordIndex tokenLines[numLines];
for(i=0; i<numLines; i++){
char* token;
int j = 0; //counter
LineAux = (char*) malloc(MAX_LENGTH*sizeof(char)); //MAX_LENGTH = 128
if (LineAux==NULL){
fprintf(stderr,"Error, malloc failed");
exit(1);
}
strcpy(LineAux,text[i]);
token = strtok(LineAux, " \n");
j++;
if(token == NULL){ //if blank line
token=" ";
} else {
while(token != NULL){ //segmentation fault
if(j == word){
break;
}
token = strtok(NULL, " \n");
j++;
}
}
strcpy(tokenLines[i].word,token);
tokenLines[i].index=i;
free(LineAux); //free Aux string
printf("token: %s Line: %d \n",tokenLines[i].word, tokenLines[i].index);
}
qsort(tokenLines,numLines,sizeof(wordIndex),compareTo); //sorting tokens
sortedText = (char**) malloc(numLines*sizeof(char*));
if (sortedText==NULL){
fprintf(stderr,"Error, malloc failed");
exit(1);
}
//reordering text
int n;
for (n=0; n<numLines; n++){
int index;
sortedText[n]=(char*) malloc(MAX_LENGHT*sizeof(char));
if (sortedText[n]==NULL){
fprintf(stderr,"Error, malloc failed");
exit(1);
}
index = tokenLines[n].index;
strcpy(sortedText[n],text[index]);
}
return sortedText;
}
the segmentation fault appears inside the while loop. Hope you can help, Thank you in advance.
text[i]ever be longer than 127 characters plus the terminating byte? Because if it can, yourstrcpyis going to overrunLineAux's bounds. Same goes fortext[index]further down.wordIndex? Some sort of struct I take it?