首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带有模板的向量在打印上下文时给出了值研中的错误

带有模板的向量在打印上下文时给出了值研中的错误
EN

Stack Overflow用户
提问于 2013-10-01 15:54:34
回答 2查看 223关注 0票数 0

我非常困惑为什么我的代码在运行val研内存检查时会出现错误:

代码语言:javascript
运行
复制
valgrind --tool=memcheck --leak-check=yes ./output

在编译和运行时,代码工作得很好。但是,在运行valgrind工具时,它最终会给出这样的信息。

错误摘要:来自9个上下文的170个错误(抑制:2来自2)

如果有人能帮我,那就太好了。

谢谢/Pete

代码语言:javascript
运行
复制
#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?
}
EN

回答 2

Stack Overflow用户

发布于 2013-10-01 16:17:17

是否在打印矢量元素之前初始化它们?对代码的此更改为我修复了valrgind错误:

代码语言:javascript
运行
复制
--- 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()调用进行注释时,我才得到了计算量错误。

票数 1
EN

Stack Overflow用户

发布于 2013-10-01 16:17:11

这是我的结果

代码语言:javascript
运行
复制
==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==

我认为,您获得的错误摘要可能来自不属于代码一部分的标题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19120733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档