c++valgrindtreap

Errors from valgrind (Treap)


Valgrind throws errors in this program when implementing the Treap data structure. Can't figure out how to fix this. Tried to write a destructor, nothing changed. The rest of the code is not included for simplicity. The error is in this part of the code.

#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

Solution

  • Explicit use of operator new and delete (or new[] and delete[]) is consider a bad practice (since C++11 is in use). It is recommended to use RAII pattern.

    In your case everything can be handled by use of std;:vector.

    class decTree {
       private:
        int treeSize;
        std::vector<vertex> vertexs;
        std::vector<pvertex> ordered;
        pvertex root;
        int vertexCount;
    
       public:
        decTree(std::istream &in) {
            int a, b;
            vertexCount = 0;
            in >> treeSize;
            vertexs.resize(treeSize);
            ordered.resize(treeSize);
            for (int i = 0; i < treeSize; i++) {
                in >> a >> b;
                ordered[vertexCount] = &vertexs[vertexCount];
                vertexCount++;
            }
        }
    };
    

    https://godbolt.org/z/co4jbcbvW