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;
}
ad absurdum
  • 19,498
  • 5
  • 37
  • 60
w33z
  • 19
  • 5

1 Answers1

1

You never allocated space for line to point to.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101