【发布时间】:2013-04-07 01:44:43
【问题描述】:
我对 C++ 内存管理很陌生,因为与 C 不同,释放所有内存有更多障碍。
我正在尝试成功删除指向任何类型向量的指针(即向量 * 数据)
/**
* We test the program in accessing vectors
* with dynamic storage
**/
#include <iostream>
#include <vector> // you must include this to use vectors
using namespace std;
int main (void){
// Now let's test the program with new and delete
// for no memory leaks with vectors (type safe)
// however, just calling delete is not enough to free all memory
// at runtime
vector <int> * test_vect = new vector <int> (10,5);
// Print out its size
cout << "The size of the vector is " << test_vect->size()
<< " elements" << endl;
// run through vector and display each element within boundary
for (long i = 0; i < (long)test_vect->size(); ++i){
cout << "Element " << i << ": " << test_vect->at(i) << endl;
}
delete test_vect;
return EXIT_SUCCESS;
}
但是,我在使用 valgrind 后出现内存泄漏
==2301== HEAP SUMMARY:
==2301== in use at exit: 4,184 bytes in 2 blocks
==2301== total heap usage: 4 allocs, 2 frees, 4,248 bytes allocated
==2301==
==2301== LEAK SUMMARY:
==2301== definitely lost: 0 bytes in 0 blocks
==2301== indirectly lost: 0 bytes in 0 blocks
==2301== possibly lost: 0 bytes in 0 blocks
==2301== still reachable: 4,096 bytes in 1 blocks
==2301== suppressed: 88 bytes in 1 blocks
如何使用指向向量的指针(即在运行时)消除所有内存泄漏痕迹?
【问题讨论】:
-
vector <int> * test_vect = ...违背了向量最初存在的目的。 -
为什么要使用带有向量的指针..?
-
“因为与 C 不同,释放所有内存存在更多障碍。”笏。
-
他是否在使用指向整数向量的指针时头脑是否正常并不是问题:看似简单的程序正在泄漏内存。让我们试着帮他找出原因,然后再告诉他为什么做一个指向向量的指针是愚蠢的。
标签: c++ memory-management vector memory-leaks