为什么会有内存泄漏? (C)

时间:2017-04-09 17:39:25

标签: c memory-leaks

this._http.get("assets/java_code.txt").map(res => res.text()).subscribe(
      response => {
        this.demoJavaCodeFromFile = response;
      },
      error => {
        this.componentErrorMessage = error;
      },
      () => {
        console.log('File successfully loaded..');
      }
    );

每次调用struct game_t { int playercount; int board_width, board_height; int turn_of;//player number int eleminatedPlayer[MAX_PLAYERS]; int turn; int cellcnt[MAX_PLAYERS]; grid_t** board; move_t* moves; }; game_t* new_game(int width, int height, int playercount) { int i; game_t* newgame; newgame = (game_t*)calloc(1,sizeof(game_t)); // <line 181 newgame->board_height = height; newgame->board_width = width; newgame->playercount = playercount; newgame->turn_of = 0;//Red(player 0) zero_fill_arr((char*)newgame->eleminatedPlayer, sizeof(int)*MAX_PLAYERS); zero_fill_arr((char*)newgame->cellcnt, sizeof(int)*MAX_PLAYERS); newgame->moves = (move_t*)calloc(MAX_MOVES, sizeof(move_t)); newgame->board = (grid_t**)calloc(width, sizeof(grid_t**)); for (i = 0; i < width; i++) { newgame->board[i] = (grid_t*)calloc(height, sizeof(grid_t)); } return newgame; } 时,此代码都会发生内存泄漏 示例:

calloc

其他信息:

该函数只被调用一次。

这段代码调用函数: WARNING: Visual Leak Detector detected memory leaks! ---------- Block 1 at 0x00EA5B20: 76 bytes ---------- Leak Hash: 0xE1234C8B, Count: 1, Total 76 bytes Call Stack (TID 3264): ucrtbased.dll!calloc() atoms.c (181): Atoms.exe!new_game() + 0xC bytes atoms.c (120): Atoms.exe!main() + 0x1A bytes f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl (64): Atoms.exe!invoke_main() + 0x1B bytes f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl (253): Atoms.exe!__scrt_common_main_seh() + 0x5 bytes f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl (296): Atoms.exe!__scrt_common_main() f:\dd\vctools\crt\vcstartup\src\startup\exe_main.cpp (17): Atoms.exe!mainCRTStartup() KERNEL32.DLL!BaseThreadInitThunk() + 0x24 bytes ntdll.dll!RtlSubscribeWnfStateChangeNotification() + 0x439 bytes ntdll.dll!RtlSubscribeWnfStateChangeNotification() + 0x404 bytes Data: 02 00 00 00 03 00 00 00 03 00 00 00 00 00 00 00 ........ ........ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ........ ........ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ........ ........ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ........ ........ 00 00 00 00 60 05 EB 00 58 6D EB 00 ....`... Xm......
game_session = new_game(w,h,playerno);初始化为NULL(0)。

1 个答案:

答案 0 :(得分:0)

所以,总结一下我学到的东西:

Visual Leak DetectorLeakSanitizer(内存泄漏检测工具)
当main函数返回时未释放内存时检测泄漏 因为大多数情况下, IS 泄漏。 C语言不适用于Garbage Collection

This Q&A清楚地显示哪些内存自动释放,哪些不是。

  

如果只是为了使检漏仪静音,你真的不必释放记忆。   但释放记忆是一种很好的做法    - n.m。

在我看来,总是释放记忆 甚至几个字节的内存泄漏也可以很快累积。