I am teaching myself c++ templates. I wrote the following code, and I am getting a weird error about a pointer being freed that wasn’t allocated. I am guessing that something in my class template constructor isn’t actually calling new on the int when I ask for an <int> type of this class. The code is being compiled and run automatically by CodeRunner for mac which I set up to use the clang++ compiler for c++ files.
#include <vector>
#include <iostream>
template <typename T>
class HeapVal
{
public:
HeapVal(T val) {ptr = new T(val);}
~HeapVal() {delete ptr;}
T get() {return *ptr;}
private:
T* ptr;
};
int main(){
std::vector< ::HeapVal<int> > vec;
for(int i = 0; i < 1000; ++i){
::HeapVal<int> h(i);
vec.push_back(h);
}
for(int i = 0; i < 1000; ++i){
std::cout << vec[i].get() << std::endl;
}
return( 0 );
}
That code results in the following error either during compilation or execution (looks to me like a run-time kind of error).
Untitled(30214) malloc: *** error for object 0x7f82f24007c0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Run Command: line 1: 30214 Abort trap: 6 ./"$2" "${@:3}"
You’re missing a copy constructor and assignment operator for
HeapVal. The implication of that is that you’ll ultimately end up trying todeletethe same memory more than once, because you have multiple pointers to it – that’s what causes the crash.Try something like this: