创建二维数组时何处释放内存?Valgrind报错问题咨询
free() Placement Hey there! Let's walk through why Valgrind is flagging that memory leak and how to fix it, plus figure out exactly where to put your free() calls when you still need to use the array in other parts of your program.
Why You're Getting the Valgrind Error
Your code correctly sets up a 2D array in two key steps:
- First, you allocate a block of memory to hold
rownumber ofint*pointers (this is the line Valgrind calls out:int **board = malloc(row*sizeof( *board));). - Then you allocate individual memory blocks for each row with
board[i] = malloc(col * sizeof(*board[i]));.
The leak happens because you're not freeing both layers of memory. Valgrind is telling you the outer block (the array of pointers) is "definitely lost"—meaning you never called free() on board itself. Even if you freed the inner row blocks, forgetting to free this outer chunk leaves that memory unclaimed.
Where to Put Your free() Calls
Since you need to use the array in other functions first, you must wait until you're completely done using every part of the 2D array before freeing it. That means:
- Run all your functions that modify or read
boardfirst. - Only after the last time you access
board(or anyboard[i][j]) should you run the free code.
The Correct Freeing Sequence
You have to free memory in reverse order of allocation: first free each individual row, then free the outer pointer array. If you do it the other way around, you'll end up with invalid (wild) pointers and undefined behavior.
Here's the exact code you need to add once you're done with the array:
// Step 1: Free each row's memory first for (int i = 0; i < r; i++) { free(board[i]); board[i] = NULL; // Optional but recommended: prevents accidental wild pointer access } // Step 2: Free the outer array of pointers free(board); board = NULL;
Quick Extra Tips
- Match loop variable types: You used
intfor your loop counter andsize_tforrow/col. For full safety (especially ifrcould be very large), consider usingsize_t iinstead ofint iin your loops—this matches the type ofrowand avoids potential overflow issues. - Handle allocation failures: If any
malloc()returnsNULL, you should clean up any already-allocated memory before exiting to avoid leaks. For example, ifboard[3]fails to allocate, you need to freeboard[0]throughboard[2]before freeingboard. - Avoid wild pointers: Setting pointers to
NULLafter freeing them is a good habit—it helps catch accidental access to freed memory later.
内容的提问来源于stack exchange,提问作者Question

