内存泄漏的这个问题,有时其实是不需要去管的,但强迫症患者总会想去修复这些不完美的地方。
问题
简单点来说,就是使用exit会导致程序强制退出作用域,像全局函数这样的可以被正常释放,但是其他就不能够保证,目前测试是设计到内部动态分配的基本都可能无法被释放,造成可能程度上的内存泄漏。
程序
执行的代码段很简单,这个函数被设置成了回调函数,在被调用后,直接终止程序,造成程序可能性上的泄漏。
void exitEvent() { exit(-1); }
检测结果
==298439==
==298439== LEAK SUMMARY:
==298439== definitely lost: 0 bytes in 0 blocks
==298439== indirectly lost: 0 bytes in 0 blocks
==298439== possibly lost: 0 bytes in 0 blocks
==298439== still reachable: 832 bytes in 15 blocks
==298439== suppressed: 0 bytes in 0 blocks
==298439==
==298439== For lists of detected and suppressed errors, rerun with: -s
==298439== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
解决
程序
要达到安全高,完美程序退出的话,还是要用return进行栈返回。线性顺序释放分配的内存空间,我这边的程序,就是需要外部进行一定的条件判断进行引导。(是一个Linux终端下的人机交互客户端)
void exitEvent() { return; }
if (cmd == "exit") return ; // 外部
检测结果
==296435==
==296435== HEAP SUMMARY:
==296435== in use at exit: 0 bytes in 0 blocks
==296435== total heap usage: 30 allocs, 30 frees, 77,240 bytes allocated
==296435==
==296435== All heap blocks were freed -- no leaks are possible
==296435==
==296435== For lists of detected and suppressed errors, rerun with: -s
==296435== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)