Search code examples
cfiledynamic-memory-allocationscanf

fscanf crashing the program as it tries to scan in rest of text file


I have a text file named dictionary, on the first line it is an int that tells us how many words are in the dictionary. After the first line it is a subsequent series of lines with a word on each.

For some reason fscanf reads in the first line (the integer) with no problem but as I try to read in the string with the loop it crashes right then and there. I am unsure what the error as visual studios just gives me an unhandled exception in some other file (I assume this is the code for the fscanf function).

#include <stdio.h>
#include <stdlib.h>
#define MAXWORDLENGTH 19
const int DX_SIZE = 8;
const int DX[] = {-1,-1,-1,0,0,1,1,1};
const int DY[]= {-1,0,1,-1,1,-1,0,1};

char** storeDictionary();

int main(void){
char** dictionary;
dictionary = storeDictionary();
system("pause");
    return 0;
}

char** storeDictionary(){
    int i;
    int j;
    FILE *fp;
    char** dictionary;
    fp = fopen("dictionary.txt", "r");
    int amountOfWords;
    fscanf(fp,"%d", &amountOfWords);
    dictionary = calloc(amountOfWords, sizeof(char*));
    for (i = 0; i < MAXWORDLENGTH; i++){
        dictionary[i] = calloc(MAXWORDLENGTH, sizeof(char*));
    }
    if (dictionary == NULL){
        printf("Allocation failed");

    }
    for(i=0; i< amountOfWords; i++){
        for (j = 0; j < MAXWORDLENGTH; j++){
            fscanf(fp, "%s", dictionary[i]);

        }
    }
    fclose(fp);
    for(i =0; i<amountOfWords;i++){
        printf("%s",dictionary[i]);
        printf("\n");

    }

    return dictionary;

}

Also I may be dynamically allocating wrong, but I've tried various ways and get the same crash at the fscanf in the loop.


Solution

  • You have the wrong loop bound here:

    for (i = 0; i < MAXWORDLENGTH; i++){
        dictionary[i] = calloc(MAXWORDLENGTH, sizeof(char*));
    }
    

    Change it to:

    for (i = 0; i < amountOfWords; i++){
        dictionary[i] = calloc(MAXWORDLENGTH, sizeof(char*));
    }
    

    Jonathan Leffler also points out that the size used in these calloc calls is wrong. sizeof(char *) should be sizeof(char) in those calls.

    Of course, you need to guarantee that each string is no more than MAXWORDLENGTH - 1 characters long.