0

I want to sort strings from file; this code compiles well, but it stops working in line 29, when I do words_array[i] = strdup(line);.

From debugger I have "program received signal sigsegv segmentation fault"

#include<stdio.h> #include<stdlib.h> #include<string.h> int comparator ( const void * elem1, const void * elem2 ) { return strcmp( *(const char**) elem1, *(const char**) elem2); } int main() { char filename[]="dane.txt"; FILE* fp; char* line = NULL; size_t len = 0; char** words_array = NULL; int i = 0,j; // number of elements // read list from file if( ( fp = fopen(filename, "r") ) == NULL ) { fprintf(stderr, "Cannot open source file %s!\n", filename); exit(1); } for(; fgets(line, len, fp) != NULL; ++i) { // put word in array words_array = realloc(words_array, sizeof(char*) * (i + 1) ); words_array[i] = strdup(line); } fclose(fp); free(line); // sort it qsort(words_array, i, sizeof(char*), comparator); if( ( fp = fopen(filename, "a+") ) == NULL ) { fprintf(stderr, "Cannot open source file %s!\n", filename); exit(1); } // write to file and free dynamically allocated memory for(j = 0; j < i; ++j) { fprintf(fp, "%s", words_array[j]); free(words_array[j]); } free(words_array); fclose(fp); return 0; } 
5
  • 1
    fgets(&line, &len, fp) != -1 --> fgets(line, len, fp) != NULL, but notice that len = 0 at this point and line doesn't have room to store the string. Commented May 29, 2017 at 18:52
  • 1
    fgets --> getline Commented May 29, 2017 at 18:54
  • strcmp( (char*) elem1, (char*) elem2) --> strcmp( *(const char**) elem1, *(const char**) elem2) Commented May 29, 2017 at 18:59
  • Ok, now i dont have any errors when i complile. However it still not reading strings from file ;/ Commented May 29, 2017 at 19:04
  • see this mentioning getline Commented May 29, 2017 at 19:20

1 Answer 1

1

You never allocated space for line to point to.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.