C++ 带有模板的向量在打印上下文时在Valgrind中出现错误
我很困惑为什么我的代码在运行valgrind内存检查时出错:C++ 带有模板的向量在打印上下文时在Valgrind中出现错误,c++,valgrind,C++,Valgrind,我很困惑为什么我的代码在运行valgrind内存检查时出错: valgrind --tool=memcheck --leak-check=yes ./output 该代码在编译和运行时运行良好。但是当运行valgrind工具时,它最终给出了这个消息 错误摘要:来自9个上下文的170个错误(已抑制:2个来自2个) 如果有人能帮我,那就太好了。 谢谢你/皮特 #include <iostream> #include <cstdlib> #include <list&g
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?
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
模板
类向量{
公众:
T*p;
大小;
公众:
向量(){
cout p=新的T[尺寸];
}
~Vector(){
这是我的结果
==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==
我认为您得到的错误摘要可能来自不属于代码的标题。您是否在打印矢量元素之前初始化了它们?对代码的此更改为我修复了ValrFind错误:
--- 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>(){
——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 @@
向量(){
cout p=新的T[尺寸];
+这->p=新的T[尺寸]();
}
~Vector(){
请注意,我只有在取消注释您的dvect.print_values()时才得到valgrind错误
call.您使用了什么类型的T
来实例化模板?如果我理解正确,那么我选择在main中使用它。但是这是我第一次使用模板,所以我对它不太了解。我确实尝试显式地将值赋给向量中的元素。它也没有错误。但是您的技术是完美的。谢谢你,我的救世主。;)你是否取消了调用print_values
的行的注释?这样做会给出报告的错误。