首页 > 解决方案 > Realloc:尝试存储字符串的下一个大小无效

问题描述

我只是在从文件中获取字符串时遇到问题。字符串每行列出一个,并受换行符的限制。我试图将它们存储在一个动态的字符串数组中,并收到一个无效的下一个大小错误,然后在第三个字符串之后中止。

我正在使用结构字典将大小存储在整数变量中,并将单词存储在字符串数组中。

代码是:

struct Dictionaries {
    char** words;
    int size;
};
typedef struct Dictionaries dictionary;

dictionary get_dict (FILE* fp) {
    dictionary* dict  =  malloc(sizeof(dictionary));
    dict->size = 0;
    int strSize = 0;
    dict->words = (char**) malloc(sizeof(char*));
    dict->words[dict->size] = malloc(sizeof(char));

    while(1) {
        char c = fgetc(fp);

        if (c == EOF ){
            break;
        }

        if (c == '\n') {
            dict->words[dict->size][strSize] = '\0';
            strSize = 0;
            dict->size++;
            dict->words[dict->size] = malloc(sizeof(char));
            dict->words = (char**) realloc(dict->words, (dict->size+1) * sizeof(char*));

        } else {
            strSize++;
            //printf("%d\n", strSize);
            //printf("%d\n", dict->size);
            dict->words[dict->size] = (char*) realloc(dict->words[dict->size], (strSize+1) * sizeof(char));
            dict->words[dict->size][strSize -1] = c;
        }
    }
    return *dict;
}

PS抱歉格式不好,我第一次使用这个网站。

标签: cmemoryrealloc

解决方案


推荐阅读