[英]Where to free memory, while creating 2d array? valgrind error
我開始學習動態 memory 分配。 在這段代碼中,我在主function 二維數組中創建了:
int r, c;
scanf("%d %d\n", &r, &c);
size_t row = (size_t) r;
size_t col = (size_t) c;
int **board = malloc(row * sizeof(*board));
for (int i = 0; i < r; i++) {
board[i] = malloc(col * sizeof(*board[i]));
}
(由於 for 循環,我需要 int 和 size_t,尤其是當 r>=0 時,這對於 size_t 總是正確的)。
然后我用其他功能更換電路板。 Valgrind 回歸:
==59075== 364 (56 direct, 308 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==59075== at 0x483577F: malloc (vg_replace_malloc.c:299)
==59075== by 0x10B4DB: main (name22.c:122)
==59075==
122行是:
int **board = malloc(row*sizeof( *board));
我想我必須使用free(),但是在檢查了我不知道的其他答案之后,我的錯誤在哪里以及將free()放在哪里,如果使用通過程序的rest使用這個表。 我會很感激你的提示和解釋。 `
當你調用int **board = malloc(row * sizeof(*board));
,系統將為您分配 memory 的row * sizeof(*board)
字節,然后返回指向該 memory 開頭的指針(即 - 一個名為 memory 變量的board
,您存儲在int **
地址中)
當你的程序完成時,系統會回收 memory,所以如果你的程序是短暫的,它可能並不重要,但是養成釋放你的 memory 的習慣是個好習慣,因為它不會回收任何 ZE299B4935619806CD直到你的程序退出,除非你告訴它。
出於這個原因,一旦你完成了 memory,你應該總是調用free(...)
,傳入你第一次調用malloc(...)
時給出的 memory 地址。 在大多數情況下,對malloc(...)
的每次調用都應該對free(...)
進行相等且相反的調用
這很重要,因為您的系統具有有限數量的 memory。 如果您的程序要求資源,然后在完成后從不歸還它們,您最終將用完 memory - 這就是所謂的“內存泄漏”。
所以對你來說,正確調用free(...)
看起來像這樣:
int **board = malloc(row * sizeof(*board));
for (int i = 0; i < r; i++) {
board[i] = malloc(col * sizeof(*board[i]));
}
// Do something with board
for (int i = 0; i < r; i++) {
free(board[i]);
}
free(board);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.