带有模板的矢量在打印上下文时在Valgrind中给出错误

时间:2013-10-01 15:54:35

标签: c++ valgrind

我很困惑为什么我的代码在运行valgrind内存检查时出错:

valgrind --tool=memcheck --leak-check=yes ./output

编译和运行时代码完美无缺。但是当运行valgrind工具时,它最终会给出这个消息。

  

错误摘要:来自9个上下文的170个错误(被抑制:2个来自2个)

如果有人可以帮助我,那就太好了 谢谢你/皮特

#include <iostream>
#include <cstdlib>
#include <list>
#include <stdexcept>
#include <algorithm>

using namespace std;

template <typename T>

class Vector{
public:
    T* p;
    size_t size;
public:
Vector<T>(){
    cout << "The default constructor" << endl;
    this-> size = 10;    // initial size
    this->    p = new T[size];

}
~Vector<T>(){
    cout << "The destructor" << endl;
    delete [] p;
}

void print_values(){
        for (unsigned i = 0; i < this->size; ++i){
            std::cout << *(this->p+i) << " ";}
        std::cout << endl;
}   

};

int main(){
Vector <double> dvect;
//dvect.print_values();   // why gives error?
}

2 个答案:

答案 0 :(得分:1)

您是否在打印前初始化矢量元素?对您的代码的这一更改为我修复了valrgind错误:

--- foo.cpp.orig    2013-10-01 09:15:30.093127716 -0700
+++ foo.cpp 2013-10-01 09:15:34.293127683 -0700
@@ -16,7 +16,7 @@
 Vector<T>(){
     cout << "The default constructor" << endl;
     this-> size = 10;    // initial size
-    this->    p = new T[size];
+    this->    p = new T[size]();

 }
 ~Vector<T>(){

请注意,当我取消注释您的dvect.print_values()电话时,我只收到了valgrind错误。

答案 1 :(得分:0)

这是我的结果

==21382==
==21382== HEAP SUMMARY:
==21382==     in use at exit: 0 bytes in 0 blocks
==21382==   total heap usage: 1 allocs, 1 frees, 80 bytes allocated
==21382==
==21382== All heap blocks were freed -- no leaks are possible
==21382==

您认为可能来自不属于您的代码的标头的错误摘要。