Memory Leak issue

Hello guys.
Appearantly my program has an issue with memory leak but I can't really find it, im not too much of an expert but these all seem just fine to me. At least one of the functions below has a memory issue and i just can't find it, I'd appriciate any help you can give.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Vektor::Vektor(const Vektor& v)
{
    pVec=0;
    nElements=0;
    *this=v;
}

Vektor::~Vektor()
{
    nElements=0;
    delete[] pVec;

}

Vektor& Vektor::operator=(const Vektor& v) {
    if (this != &v){
        delete[] pVec;
        nElements = v.nElements;
        pVec = new double[nElements];
        for (unsigned int i = 0; i < nElements; i++)
            pVec[i] = v.pVec[i];
    }
    return *this;
}


double& Vektor::operator[](unsigned int idx){
    if (idx >= nElements || idx<0)
       throw "Error";
    return pVec[idx];
}

const double& Vektor::operator[](unsigned int idx) const {
    if (idx >= nElements || idx<0)
       throw "Error";
    return pVec[idx];
}

Vektor operator*(double val, const Vektor& vec){
    Vektor v;
    v.nElements=vec.nElements;
    v.pVec=new double[v.nElements];
    for(int i=0;i<v.nElements;i++){
        v.pVec[i]=val*vec.pVec[i];
    }
    return v;
}

operator* is a friend function that's why it has no Vektor:: in front of it so you don't have to point that out.
You have not shown the default constructor. Does it allocate an array?
I'm sorry, and it does.
here it is:
1
2
3
4
5
    Vektor(unsigned int size = defSize, double value = defValue) :nElements(size) {
        pVec = new double[nElements];
        for (unsigned int i = 0; i < nElements; i++)
            pVec[i] = value;
    }
Last edited on
$ valgrind --leak-check=full ./a.out

==2719== HEAP SUMMARY:
==2719==     in use at exit: 104 bytes in 1 blocks
==2719==   total heap usage: 4 allocs, 3 frees, 416 bytes allocated
==2719== 
==2719== 104 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2719==    at 0x4C293B0: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2719==    by 0x400B0E: Vektor::Vektor(unsigned int, double) (leak.cpp:66)
==2719==    by 0x400A0C: operator*(double, Vektor const&) (leak.cpp:56)
==2719==    by 0x400BBF: main (leak.cpp:73)


1
2
3
4
Vektor operator*(double val, const Vektor& vec){
    Vektor v; //default constructor, allocation of defSize elements
    v.nElements=vec.nElements;
    v.pVec=new double[v.nElements]; //memory leak 



consider using std::valarray
Topic archived. No new replies allowed.