C++ - 从 valgrind 中删除无效

C++ - Invalid delete from valgrind

我有一个低级模板 class,还有另一个 class,其中包含指向此 class 实例的指针。代码编译正确,但我 运行 通过 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)

您可以在下面找到 class 个文件,请注意我已经删除了与内存分配无关的代码。

这是列表 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

这是 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

最后是主要方法:

#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);
}

整个程序执行完毕,然后遇到错误

您应该使用 delete[],因为您使用 new[] 作为 int_array:

...
public:
  List() {int_array=new T[10];}
  ~List() {delete[] int_array;}
                 ~~
...

顺便说一句:你正在做的是UB。 $5.3.5/2 删除[expr.delete](我强调的):

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.

错误消息为您提供了线索:如果您创建一个数组,您可以使用以下方法删除它:

delete[] int_array;

您目前拥有的:

delete int_array;

只会删除指向数组头部的指针。