Does anyone know why is my program crashing?

I am trying to dynamically allocate words straight out of a txt file for further use, but after entering the file name, the program crashes and returns a negative value (CodeBlocks). Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define L 18
#define F 50    
int main()
    {
        char **text = NULL;
        int wcount=0;
        text = textInput(&wcount);
        free(text);
    
        return 0;
    }
    
    char** textInput(int *wcount)
    {
        FILE *loadfile;
        char fname[F];
        char *word;
        char **text;
        printf("\nType the file of the name you would like to load: ");
        scanf("%49s", fname);
        strcat(fname, ".txt");
        if((loadfile = fopen(fname, "rt")) == NULL)
            perror("Cannot open file");
        while(fscanf(loadfile,"%18s", word = (char*)malloc(L*sizeof(char)))!= EOF)
        {
            (*wcount)++;
            text = (char**)realloc(text, (*wcount)*sizeof(char *));
            text[(*wcount)-1] = word;
        }
        fclose(loadfile);
        free(word);
        return text;
    }

>Solution :

In the function textInput, you haven’t initialized text before calling realloc(text, ...).
Add the initialization text = NULL before calling realloc. E.g.

char **text = NULL;

You already have a line like that in main(), but in main() it doesn’t matter, the variable text in main() is not the same as the variable text in textInput(). (Also, in main(), you reassign text before you attempt to use it, so the initialization of text to NULL is not required.)

Leave a Reply