[英]malloc error: incorrect checksum for freed object in struct for reading file
所以我有這個功能:
source_t * source_init(char * argsource)
{
source_t * temp = (source_t *) malloc(sizeof(source_t *));
temp->path = realpath(argsource, NULL);
temp->dir = dirname(temp->path);
temp->name = basename(temp->path);
temp->ext = strrchr(temp->name, '.');
temp->content = read_file(temp->path); // here
temp->error = error_free();
return temp;
}
它正在調用函數read_file()
:
char * read_file(char * sourcepath)
{
char * buffer = NULL;
long string_size, read_size;
FILE * file = fopen(sourcepath, "r");
fseek(file, 0, SEEK_END);
string_size = ftell(file);
rewind(file);
buffer = (char *) malloc(sizeof(char) * (string_size + 1) );
read_size = fread(buffer, sizeof(char), string_size, file);
buffer[string_size] = '\0';
if (string_size != read_size)
{
free(buffer);
buffer = NULL;
}
fclose(file);
return buffer;
}
並出現此錯誤: malloc: *** error for object 0x7faf08402698: incorrect checksum for freed object - object was probably modified after being freed.
因此,當前的解決方案是在主函數中調用source_init()
之后分別初始化content
。 盡管該解決方案可行,但我希望在source_init()
初始化content
。 而且似乎我不能直接調用source_init()
初始化content
因為出現相同的錯誤,因此我必須創建一個緩沖區來調用source_init()
並將content
初始化為緩沖區。
這可能不是您想要執行的操作:
source_t * temp = (source_t *) malloc(sizeof(source_t *));
這樣就為指向 source_t對象的指針或為source_t對象分配了空間。
同樣,在C語言中,您不應該轉換malloc的返回值。 這樣做會隱藏錯誤,並使它們很難被發現。
擴展托馬斯的答案
calloc
malloc
, calloc
或realloc
。 那只是掩蓋了潛在的錯誤 sizeof(<data type>)
。 很容易犯錯誤,並使代碼的重構成為痛苦。 改用這個
source_t *temp = malloc(sizeof *temp);
這樣做的好處是sizeof *temp
返回的字節數完全正確,您不必考慮正確的類型(例如,當您處理雙/三指針時),並且如果必須更改數據類型,可以說到source2_t
,則只需更改變量的類型,而不必擔心容易被忽略的討厭的sizeof(<data type>)
。
在malloc()行的source_init()中,您有一個錯誤。
應該是: source_t * temp = (source_t *) malloc(sizeof(source_t));
而不是: source_t * temp = (source_t *) malloc(sizeof(source_t *));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.