c++ - 带有模板的 vector 在打印上下文时在 Valgrind 中给出错误

标签 c++ valgrind

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

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

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

ERROR SUMMARY: 170 errors from 9 contexts (suppressed: 2 from 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?
}

最佳答案

您是否在打印 vector 元素之前对其进行初始化?对您的代码所做的更改为我修复了 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 错误。

关于c++ - 带有模板的 vector 在打印上下文时在 Valgrind 中给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19120733/

相关文章:

使用 Valgrind 检查内存

profiling - 使用 Valgrind 获取指令配置文件

c - 分析valgrind输出: "invalid free()"

c - realloc,堆内存泄漏

C++ NetBeans Win32 hwnd 图标

c++ - 带贝塞尔曲线的 Cocos 2d-x 中的圆角矩形

c++ - 如何在C++中实现继承并解决错误 "parent class is not accessible base of child class"?

c++ - 查找索引数据结构,如 `std::vector`(不是数组)

c - valgrind 在打印分配的字符串时报错

c++ - 如何在不使用指针的情况下实现引用中的链表