gpt4 book ai didi

C++ - 从 valgrind 中删除无效

转载 作者:搜寻专家 更新时间:2023-10-31 00:58:00 24 4
gpt4 key购买 nike

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

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

这是列表类:

#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 类:

#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[] 因为你对 int_array 使用了 new[]:

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

关于C++ - 从 valgrind 中删除无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36274522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com