简体   繁体   English

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

[英]Vector with template gives error in Valgrind when printing the context

I am very confused why my code gives error when running the valgrind memory check: 我很困惑为什么我的代码在运行valgrind内存检查时给出错误:

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

The code works perfectly when compile and run. 该代码在编译和运行时完美运行。 But when running the valgrind tool it gives this message in the end. 但是,当运行valgrind工具时,它最终会显示此消息。

ERROR SUMMARY: 170 errors from 9 contexts (suppressed: 2 from 2) 错误摘要:来自9个上下文的170个错误(禁止显示:2个中的2个)

It would be wonderful if someone could help me out. 如果有人可以帮助我,那将是很棒的。
Thank you /Pete 谢谢/皮特

#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?
}

Are you initializing your vector elements before printing them? 是否在打印矢量元素之前对其进行初始化? This change to your code fixed the valrgind errors for me: 对您代码的此更改为我修复了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>(){

Note that I only got the valgrind errors when I uncommented your dvect.print_values() call. 请注意,当我取消注释您的dvect.print_values()调用时,只会收到valgrind错误。

this is my result 这是我的结果

==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==

the error summary you got I think may from the headers which are not part of your code. 我认为您得到的错误摘要可能来自不属于您代码的标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM