I am very confused why my code gives error when running the valgrind memory check:
valgrind --tool=memcheck --leak-check=yes ./output
The code works perfectly when compile and run. But when running the valgrind tool it gives this message in the end.
ERROR SUMMARY: 170 errors from 9 contexts (suppressed: 2 from 2)
It would be wonderful if someone could help me out.
Thank you /Pete
#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?
}
Are you initializing your vector elements before printing them? This change to your code fixed the valrgind errors for me:
--- 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>(){
Note that I only got the valgrind errors when I uncommented your dvect.print_values()
call.
this is my result
==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==
the error summary you got I think may from the headers which are not part of your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.