Reputation: 425
I have a low level template class, and another class which contains a pointer to an instance of this class. The code compiles correctly, but I run into the below error when running it through valgrind:
==2642== Invalid free() / delete / delete[] / realloc()
==2642== at 0x4C2A360: operator delete(void*) (vg_replace_malloc.c:507)
==2642== by 0x4125B4: List<std::string>::~List() (in /home/alex/Documents/Documents/cpp/object_module/obj_test)
==2642== by 0x411CB0: Obj3::~Obj3() (in /home/alex/Documents/Documents/cpp/object_module/obj_test)
==2642== by 0x410AC1: main (in /home/alex/Documents/Documents/cpp/object_module/obj_test)
==2642== Address 0x5a02878 is 8 bytes inside a block of size 88 alloc'd
==2642== at 0x4C298A0: operator new[](unsigned long) (vg_replace_malloc.c:389)
==2642== by 0x4124FE: List<std::string>::List() (in /home/alex/Documents/Documents/cpp/object_module/obj_test)
==2642== by 0x411BC6: Obj3::Obj3(std::string, std::string, std::string, std::string, std::string) (in /home/alex/Documents/Documents/cpp/object_module/obj_test)
==2642== by 0x41065A: main (in /home/alex/Documents/Documents/cpp/object_module/obj_test)
You can find the class files below, please note that I've stripped out code not relevant to memory assignment.
Here's the List class:
#ifndef LIST_H
#define LIST_H
template <class T>
class List
{
T *int_array;
...
public:
List() {int_array=new T[10];}
~List() {delete int_array;}
...
};
#endif
Here's the Obj3 class:
#ifndef OBJ3_H
#define OBJ3_H
#include <string>
#include "list.h"
class Obj3
{
private:
//A list of scenes
List <std::string> *scene_list;
...
public:
//Constructors & Destructor
Obj3() {scene_list = new List <std::string>;}
~Obj3() {delete scene_list;}
...
#endif
And, finally, the main method:
#include "obj3.h"
void print_obj_attributes(Obj3& obj)
{
std::cout << obj.get_name() << std::endl;
...
}
int main()
{
Obj3 obj2;
std::cout << "Object 2" << std::endl;
print_obj_attributes(obj2);
}
The entire program executes, and then the error is encountered.
Upvotes: 2
Views: 1616
Reputation: 172924
You should use delete[]
because you used new[]
for int_array
:
...
public:
List() {int_array=new T[10];}
~List() {delete[] int_array;}
~~
...
BTW: What you're doing is UB. $5.3.5/2 Delete [expr.delete] (emphasized by me):
In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined.
Upvotes: 4
Reputation: 505
The error message is giving you the clue: if you create an array you delete it with:
delete[] int_array;
What you currently have:
delete int_array;
Will only delete the pointer pointing to the head of the array.
Upvotes: 0