簡體   English   中英

正確的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;
};

編輯2

我最終得出結論,它可以完美運行(名稱不言自明)。

conf_init()

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

conf_load() ,其中pchstrtok()返回的字符串

conf->table[i].name = malloc(sizeof(char)*strlen(pch));
conf->table[i].name = pch;

我希望這足以為下一個解釋:)

恐怕,不。

假設您提到的字符串的形式為

struct Categorie
{

.
.
char * str;
}

您應該先使用sizeof(struct Categorie) conf->table的內存conf->tablemalloc() ,然后將conf->table->str malloc() conf->table->str

更不用說在完全相反的分配順序中也需要free() ,即,首先需要釋放conf->table->str ,然后conf->table

答:不可以。

您需要提供更多代碼來了解發生了什么,但是假設conf->tablestruct Categorie *那么有些爛了。

如果不是這種類型,則不清楚為什么您曾經以為sizeof(struct Categorie)是答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM