我刚刚写了一段 C++ 代码,用于字符串操作,但是当我使用 valgrind 进行检查时,发现可能存在内存泄漏。我对代码进行了深度调试,并写了一个类似这样的简单 C++ 程序:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
std::string myname("Is there any leaks");
exit(0);
}
并且在运行valgrind时我得到了:
==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);
}
main()
返回一个值时,它实际上不是一个int
。它会被转换为有效的退出代码范围,即[0,256)
(至少对于 Posix)。 - moooeeeep