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.
CodePudding user response:
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, "