适当的 malloc 错误修复

proper malloc bug fixing

我有这行代码:

conf->table = malloc(sizeof(struct Categorie)*(csv_nbLines(filename)));

conf 上调用 free() 时导致错误,因为 struct Categorie 包含一个字符串(char 的数组)。

我通过将 sizeof(struct Categorie) 替换为 30 来修复错误,因为我知道所述字符串不会超过 30 个字节。

这可以接受吗?如果不是,什么是 malloc 所需的确切内存量的更好方法?

编辑 :

struct Categorie {
    char *name;
    char c;
};

EDIT2 :

我最终得到了这个并且它完美地工作(名字不言自明)。

conf_init()

conf->table = malloc(sizeof(struct Categorie))

in conf_load() 其中 pch 是由 strtok()

返回的字符串
conf->table[i].name = malloc(sizeof(char)*strlen(pch));
conf->table[i].name = pch;

我希望这足以解释下一个 :)

恐怕不行

假设你提到的字符串的形式是

struct Categorie
{

.
.
char * str;
}

你应该首先 malloc() conf->table 的记忆 sizeof(struct Categorie),然后 malloc() conf->table->str

更不用说,free()ing 也需要,在完全相反的分配顺序中,即首先你需要释放 conf->table->str 然后 conf->table.

回答:不行,那不行。

您需要提供更多代码来理解发生了什么,但假设 conf->tablestruct Categorie * 那么有些东西很糟糕。

如果这不是那种类型,那么不清楚您为什么认为 sizeof(struct Categorie) 可能是答案。