簡體   English   中英

帶模板的矢量在打印上下文時在Valgrind中給出錯誤

[英]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==

我認為您得到的錯誤摘要可能來自不屬於您代碼的標頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM