問題
Valgrind 通知我記憶體泄漏,但是無論如何我似乎都無法弄清楚我是如何沒有釋放所有分配的記憶體,這導致了我的標題中的問題。我不會提供我的完整代碼,所以我也不會附上整個 valgrind 報告,但我會指出 valgrind 認為問題出在哪里。
一些代碼可以進一步解釋發生了什么
假設檢查所有記憶體分配是否有錯誤,假設 while 回圈最終終止
struct s1{
int total_s2; // assume some code initialise this to 0
struct s2 **arr_s2;
} struct1;
struct s2{
char *important_string
};
void add_s2_to_s1(struct s2 *struct2){
struct1.arr_s2 = realloc(s1.arr_s2, sizeof(struct s2 *) * s1.total_s2);
struct1.arr_s2[total_s2 - 1] = malloc(sizeof(struct s2)); // !mem lost!
struct1.arr_s2[total_s2 - 1] = struct2;
}
// in main
while(some_string){
struct s2 *struct2 = malloc(sizeof(*struct2));
struct2->important_string = malloc(sizeof(some_string) 1);
s1.total_s2 ;
add_s2_to_s1(struct2);
// some code to change some_string
}
for(int i = 0; i < total_s2; i ){
free(s1.arr_s2[i]->important_string);
free(s1.arr_s2[i]);
}
free(s1.arr_s2);
多一點我的理解
盡管struct2從技術上講,while 回圈的每次迭代都會丟失,但指向記憶體的指標struct2應該存盤在陣列中struct1,因此應該可以毫無問題地被釋放。
記憶體泄漏問題最糟糕的部分是我的程式正在做我希望它現在做的事情,所以我很想把手舉到空中繼續前進。但我知道我應該修好它,否則它可能會回來咬我的屁股。
uj5u.com熱心網友回復:
此行分配一些位元組并將指向這些位元組的指標存盤在變數中struct1.arr_s2[total_s2 - 1]:
struct1.arr_s2[total_s2 - 1] = malloc(sizeof(struct s2)); // !mem lost!
這一行存盤了一個指向變數中其他位元組的指標struct1.arr_s2[total_s2 - 1]:
struct1.arr_s2[total_s2 - 1] = struct2;
如您所知,一個變數一次只有一個值。該變數struct1.arr_s2[total_s2 - 1]現在包含與該變數相同的值struct2- 它不記得您給它的另一個值(一些新分配的位元組的地址)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/473146.html
