我刚写了一个C++代码,它做了一些字符串操作,但是当我运行ValgRing时,它显示了一些可能的内存泄漏.将代码调试成颗粒状级别I编写了一个简单的C++程序,看起来像:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
std::string myname("Is there any leaks");
exit(0);
}
在这上面我看到:
==20943== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 26 from 1)
==20943== malloc/free: in use at exit: 360,645 bytes in 12,854 blocks.
==20943== malloc/free: 65,451 allocs, 52,597 frees, 2,186,968 bytes allocated.
==20943== For counts of detected errors, rerun with: -v
==20943== searching for pointers to 12,854 not-freed blocks.
==20943== checked 424,628 bytes.
==20943==
==20943== LEAK SUMMARY:
==20943== definitely lost: 0 bytes in 0 blocks.
==20943== possibly lost: 917 bytes in 6 blocks.
==20943== still reachable: 359,728 bytes in 12,848 blocks.
==20943== suppressed: 0 bytes in 0 blocks.
==20943== Reachable blocks (those to which a pointer was found) are not shown.
==20943== To see them, rerun with: --show-reachable=yes
然后我突然意识到我们已经强制退出了(我也是在我的原始C++代码中执行的).现在的问题是,我想退出程序,因为我之前的旧代码正在等待新代码的退出状态.例如,二进制a.out等待b.out的退出状态.有没有办法避免内存泄漏,或者我真的应该担心内存泄漏,因为程序在那个时候已经退出了.
这也给我提出了另一个问题,这样的规范有害吗?
#include<stdio.h>
#include<cstdlib>
int main()
{
char *p=(char *)malloc(sizeof(char)*1000);
exit(0);
}