不清楚的内存泄漏与向量,c++,当调用退出
unclear memory leak with vector, c++, when calling exit
我正在调试我的程序,我注意到,即使我已经标记了几乎所有的它作为注释,我所做的就是将双精度值推入向量,我有内存泄漏。我在c++参考中阅读了api,但找不到任何东西。下面是代码:
#include <vector>
#include <cstdlib>
#include <iostream>
#include "RegMatrix.h"
#include "Matrix.h"
using namespace std;
int main(void)
{
vector<double> v;
for (int i=0; i<9; i++)
{
v.push_back(i);
}
cout << endl;
exit(EXIT_SUCCESS);
}
和valgrind的报告:
==9299== HEAP SUMMARY:
==9299== in use at exit: 128 bytes in 1 blocks
==9299== total heap usage: 5 allocs, 4 frees, 248 bytes allocated
==9299==
==9299== 128 bytes in 1 blocks are still reachable in loss record 1 of 1
==9299== at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255)
==9299== by 0x804937D: __gnu_cxx::new_allocator<double>::allocate(unsigned int, void const*) (in /home/yotamoo/workspace/ex3/main)
==9299== by 0x804922F: std::_Vector_base<double, std::allocator<double> >::_M_allocate(unsigned int) (in /home/yotamoo/workspace/ex3/main)
==9299== by 0x8048E6C: std::vector<double, std::allocator<double> >::_M_insert_aux(__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, double const&) (in /home/yotamoo/workspace/ex3/main)
==9299== by 0x8048CA2: std::vector<double, std::allocator<double> >::push_back(double const&) (in /home/yotamoo/workspace/ex3/main)
==9299== by 0x8048B10: main (in /home/yotamoo/workspace/ex3/main)
==9299==
==9299== LEAK SUMMARY:
==9299== definitely lost: 0 bytes in 0 blocks
==9299== indirectly lost: 0 bytes in 0 blocks
==9299== possibly lost: 0 bytes in 0 blocks
==9299== still reachable: 128 bytes in 1 blocks
==9299== suppressed: 0 bytes in 0 blocks
这很奇怪。什么好主意吗?由于
exit()
不会调用当前作用域的析构函数,因此可能存在泄漏:
(§3.6.1/4)调用在
<cstdlib>
(18.3)中声明的函数void exit(int);
将在不离开当前块的情况下终止程序,因此不会破坏任何具有自动存储持续时间的对象(12.4)。如果在销毁具有静态存储持续时间的对象期间调用exit来结束程序,则该程序具有未定义行为。
用这个代替:
#include <vector>
#include <iostream>
int main(int argc, char *argv[]) {
std::vector<double> v;
for (int i=0; i<9; i++) {
v.push_back(i);
}
std::cout << endl;
return 0;
}
vector永远不会超出退出作用域。
将exit()
从main中移除并替换为return 0;
我不相信您有内存泄漏。当valgrind说内存仍然可以访问时,它并不是在告诉你内存泄露了,而是在程序退出之前内存没有被释放。在这种情况下,vector析构函数在退出之前没有被调用。尝试从main返回而不是调用exit()。
您是否尝试将exit
以外的所有代码放在单独的{}
块中?
你不必调用退出函数,它会立即退出程序,不调用操作系统清理调用。
始终使用return()而不是exit()
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 函数何时会在c++中包含stack_Unwind_Resume调用