首页 > 解决方案 > 来自 valgrind (Treap) 的错误

问题描述

Valgrind 在实现 Treap 数据结构时会在该程序中抛出错误。无法弄清楚如何解决这个问题。试图写一个析构函数,没有任何改变。为简单起见,不包括其余代码。错误出现在这部分代码中。

#include <iostream>
#include <fstream>

using namespace std;
ifstream in("input.txt");
ofstream out("output.txt");

class vertex{
    public:
    int x, y, label;
    struct vertex *parent, *left, *right;
    vertex() {}
};

typedef vertex *pvertex;

class decTree{
    private:
    int treeSize;
    vertex *vertexs;
    pvertex *ordered;
    pvertex root;
    int vertexCount;

    public:
    decTree(){
        int a , b;
        vertexCount = 0;
        in >> treeSize;
        vertexs = new vertex[treeSize];
        ordered = new pvertex[treeSize];
        for (int i = 0; i < treeSize; i++ ){
            in >> a >> b;
            ordered[vertexCount] = vertexs + vertexCount;
            vertexCount++;
        }
    }
};

int main(){
    decTree *mytree = new decTree;
    delete mytree;
}

///////////////////////////////////////// ////////////////

==20464== HEAP SUMMARY:
==20464==     in use at exit: 336 bytes in 2 blocks
==20464==   total heap usage: 8 allocs, 6 frees, 90,408 bytes allocated
==20464== 
==20464== 336 (56 direct, 280 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==20464==    at 0x483E217: operator new[](unsigned long) (vg_replace_malloc.c:579)
==20464==    by 0x1094A3: decTree::decTree() (in a.out)
==20464==    by 0x1092AC: main (in a.out)
==20464== 
==20464== LEAK SUMMARY:
==20464==    definitely lost: 56 bytes in 1 blocks
==20464==    indirectly lost: 280 bytes in 1 blocks
==20464==      possibly lost: 0 bytes in 0 blocks
==20464==    still reachable: 0 bytes in 0 blocks
==20464==         suppressed: 0 bytes in 0 blocks
==20464== 
==20464== For lists of detected and suppressed errors, rerun with: -s
==20464== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from

标签: c++valgrindtreap

解决方案


我添加了

~ decTree () { 
   delete [] vertices; 
   delete [] ordered; 
} 

一切正常。


推荐阅读