带有模板的矢量在打印上下文时在瓦尔格林德中给出错误
Vector with template gives error in Valgrind when printing the context
我很困惑为什么我的代码在运行 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?
}
您是否在打印矢量元素之前对其进行初始化? 对代码的更改为我修复了 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 错误。
这是我的结果
==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==
我认为您获得的错误摘要可能来自不属于您代码的标头。
相关文章:
- CPP 中的瓦尔格林德和记忆泄漏:"Conditional jump or move depends on uninitialised values"
- 删除堆后对瓦尔格林德错误感到困惑
- 瓦尔格林德报告在 =带有嵌套shared_ptrs的运算符上的读取错误
- 瓦尔格林德错误 - 地址0x0不是堆叠的 malloc'd 或自由的
- 瓦尔格林德错误来自 boost::asio
- 在瓦尔格林德的泄漏摘要中使用 std::ios::sync_with_stdio(fasle) 打印时获取"still reachable"
- 修复了瓦尔格林德错误内存泄漏的错误
- 3D 阵列中的瓦尔格林德错误C++
- 瓦尔格林德:构造函数中大小为 1 的无效读取
- 访问字符串::c_str()的结果时出现瓦尔格林德内存访问错误
- 瓦尔格林德在组成中报告的内存泄漏
- 段错误,但不是在瓦尔格林德或GDB中
- 我应该如何修复瓦尔格林德的未初始化值错误?
- 二叉搜索树瓦尔格林德错误"Invalid read of size 8"
- C++赋值构造函数瓦尔格林德错误
- 这种瓦尔格林德在加密++中使用大小为8的单位化值是真实的还是红鲱鱼
- C++内存泄漏检查中的瓦尔格林德错误
- 带有模板的矢量在打印上下文时在瓦尔格林德中给出错误
- 我如何理解瓦尔格林德中的无效读取,其中地址大于分配的块大小
- 瓦尔格林德无法检测到的malloc_consolidate (malloc.c) 中的分段错误