Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading