有谁知道为什么我的程序崩溃了?

Does anyone know why is my program crashing?

我试图直接从 txt 文件动态分配单词以供进一步使用,但在输入文件名后,程序崩溃并且 returns 一个负值 (CodeBlocks)。这是代码:

#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;
    }

在函数 textInput 中,您在调用 realloc(text, ...) 之前尚未初始化 text。 在调用realloc之前添加初始化text = NULL。例如

char **text = NULL;

你在main()里已经有这样一行了,但是在main()里没关系,main()里的变量texttextInput() 中的变量 text。 (此外,在 main() 中,您在尝试使用它之前重新分配 text,因此不需要将 text 初始化为 NULL。)