0

I don't know why but my code prints a list of (null)(null)(null).... I have to print the list of words from a file 'words.txt'. Another question is: fscanf ignore white spaces?

#define WORD_LENGTH 1024
#define SIZE_QUOTE 100

int main(){
  char **quote = malloc(sizeof(char*) * (size_t)SIZE_QUOTE);
  long i;
  for(i = 0; i < SIZE_QUOTE; i++){
    if(!(malloc(sizeof(char) * (size_t)WORD_LENGTH)))
      exit(1);
  }
  i = 0;
  FILE *pf = fopen("words.txt", "r");
  while(!feof(pf) && i < SIZE_QUOTE){
    fscanf(pf, "%s", quote[i]);
    printf("%s", quote[i]);
    i++;
  }
  fclose(pf);
  free(quote);
}
  • 1
    Please read this [feof in while loop is bad](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – Ed Heal May 03 '18 at 21:05
  • 1
    ... and check the return value from `fopen` and `fsanf`. See manual pages for that – Ed Heal May 03 '18 at 21:06
  • ...and the return value from `malloc()`. – jmc May 04 '18 at 00:11
  • Unless each word is `1023` characters long -- that is a horribly memory inefficient way to store information. When you read a word, you can easily get its `strlen()` and then allocate `strlen() + 1` chars to store each word. Otherwise you might as well just use a `100x1024` 2D array. – David C. Rankin May 04 '18 at 01:49

1 Answers1

1

You're never assigning the return value of malloc() to quote[i] so they end up staying NULL (if you're lucky):

  char **quote = malloc(sizeof(char*) * (size_t)SIZE_QUOTE);
  long i;
  for(i = 0; i < SIZE_QUOTE; i++){
    if(!(malloc(sizeof(char) * WORD_LENGTH)))

It should be something like this instead:

  char **quote = malloc(sizeof(char*) * (size_t)SIZE_QUOTE);
  for(int i = 0; i < SIZE_QUOTE; i++){
    quote[i] = malloc(sizeof(char) * WORD_LENGTH);
    if(!quote[i])

Also you could avoid malloc() entirely and statically initialize that array if all the sizes are known:

char quote[SIZE_QUOTE][WORD_LENGTH] = {{'\0'}};

Also, you should be free()-ing the individual quote[i] at the end too:

for(int i = 0; i < SIZE_QUOTE; ++i) free(quote[i]);
free(quote);

There's other mistakes that have been pointed out through the comments already, so I won't elaborate further.

jmc
  • 540
  • 3
  • 11