检查是否释放了数组/ 2d数组/结构数组/字符串数组

时间:2015-12-11 15:39:47

标签: c free

有没有办法检查阵列是否已完全释放且没有留下任何东西? Valgrind只说有一些不确定的块。是调试器还是类似的东西?

1 个答案:

答案 0 :(得分:2)

所以,不,没有办法知道你是否通过查看指针来释放所有东西。您必须知道您的数据结构和算法,并知道何时释放已分配的内存。

在Windows(MSC)下,我使用以下内容检查程序何时终止,如果我已释放所有已分配的内存:

// Check heap upon exit: all memory freed and not corrupted?
#include <crtdbg.h>
_CrtMemState memStateStart, memStateEnd, memStateDelta;

int WinMain(...
{
    ...
    // Make a checkpoint of the heap's state so we can later check the heap is still OK
   _CrtMemCheckpoint( &memStateStart );

   ghMainWnd = CreateWindow(                           // Create the app. main window
           ...
   );
   ...
}
...
WndProc(hWnd, msg,...)
{
    ...
            case WM_CLOSE:
                    // Check the heap
                    _CrtMemCheckpoint( &memStateEnd );
                    _CrtSetReportMode( _CRT_WARN,   _CRTDBG_MODE_WNDW );
                    _CrtSetReportMode( _CRT_ERROR,  _CRTDBG_MODE_WNDW );
                    _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_WNDW );
                    if (_CrtMemDifference( &memStateDelta, &memStateStart, &memStateEnd ))
                        _CrtMemDumpStatistics( &memStateDelta );
                    _CrtDumpMemoryLeaks();
                    DestroyWindow (hWnd);
                    return (0);