1

So I gotta make this program that reads a huge .txt file into an AVL, and for that, I need to read all the formatted data in the text document and put it into an AVL. However, any time I try to initialize the AVL in my code (a NULL pointer) it breaks the code once it reaches the fscanf function I used to gather the strings out of the .txt file. I made this demo right here, and I think I'm pretty close to the source of the problem. I narrowed it down to being related to initializing a pointer with a NULL value before the fscanf function. But how do I fix this?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    FILE * filePointer = fopen("_lexico_shuf.txt", "r");

    if(!filePointer) {
        printf("can't open the file");
        exit(101);
    }

    char *lexiconWord;
    float polarity;

    int *a = NULL;
    printf("before while");
    while (!feof(filePointer)) {
        fscanf(filePointer, "%[^;];%f\n", lexiconWord, &polarity);
        printf("| (%s) (%.1f) |", lexiconWord, polarity);
    }
    printf("after while");

}

so the only thing that is printed on the screen is the "before while" printf, and not the "after while" one. and the program returns a random number.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    Before using the result of `fscanf`, you should verify that the function was successful. See this question for further information: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/q/5431941/12149471) – Andreas Wenzel Nov 18 '21 at 16:40
  • Please [edit] and format your code properly and show the first 8-9 lines of your `_lexico_shuf.txt` file. – Jabberwocky Nov 18 '21 at 16:40
  • Lucas Nascimento, Who or what text suggest code like `while (!feof(filePointer)) {`? – chux - Reinstate Monica Nov 18 '21 at 16:53
  • Closed for wrong primary reason. OP's main issue is `lexiconWord` is uninitialized when `fscanf(filePointer, "%[^;];%f\n", lexiconWord, ...` called. – chux - Reinstate Monica Nov 18 '21 at 16:58

1 Answers1

2

lexiconWord hasn't been set to point anywhere, so fscanf is using an invalid pointer value to attempt to write to.

Change this variable to an array, and use a field width in fscanf do you don't overrun the buffer, and check the return value of fscanf.

char lexiconWord[100];
...
int rval = fscanf(filePointer, "%99[^;];%f\n", lexiconWord, &polarity);
if (rval != 2) {
    printf("not all values read\n");
    exit(1);
}

Also, see Why is “while ( !feof (file) )” always wrong?

dbush
  • 205,898
  • 23
  • 218
  • 273