### 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.
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647`` ``````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

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:
 ``12345`` `````` 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)```

 ``1234`` ``````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.