gpt4 book ai didi

c++ - 复制构造函数和重载赋值运算符的堆损坏错误

转载 作者:行者123 更新时间:2023-11-28 00:21:20 25 4
gpt4 key购买 nike

我是一名学生,所以对于没有使用正确的论坛协议(protocol),我深表歉意。我已经在这个问题上搜索了几个小时,我的同学都帮不上忙。我的任务是在 C++ 中创建复制构造函数、重载赋值运算符 (=) 和析构函数(“三巨头”)来管理堆上的数组。我在 VS13 下面写的内容产生了正确的输出,但我得到了一个调试错误:HEAP CORRUPTION DETECTED:c++ crt detected that the application wrote to memory after end of heap buffer谁能给我一些指导,我什至不知道去哪里找。谢谢!!

//copy constructor

myList::myList(const myList& source){
cout << "Invoking copy constructor." << endl;
array_capacity = source.array_capacity; //shallow copy
elements = source.elements; //shallow copy
delete[] arrayPointer;
arrayPointer = new double(source.array_capacity); //deep copy

for (int i = 0; i < array_capacity; i++) //copy array contents
{
arrayPointer[i] = source.arrayPointer[i];
}
}

//overloaded assignment operator
myList& myList::operator=(const myList& source){

cout << "Invoking overloaded assignment." << endl;

if (this != &source){

array_capacity = source.array_capacity; //shallow copy

elements = source.elements; //shallow copy

delete[] arrayPointer; //delete original array from heap

arrayPointer = new double(array_capacity); //deep copy

for (int i = 0; i < source.array_capacity; i++) {//copy array contents
arrayPointer[i] = source.arrayPointer[i];
}
}
return *this;
}

//destructor
myList::~myList(){

cout << "Destructor invoked."<< endl;

delete[] arrayPointer; // When done, free memory pointed to by myPointer.

arrayPointer = NULL; // Clear myPointer to prevent using invalid memory reference.
}

最佳答案

您的代码存在一些问题。首先,您在 arrayPointer 上调用 delete,但它尚未初始化为任何内容。实际上,这可能最终会删除您已经分配的内存,或者在 delete 的实现中导致异常或 Assets 。其次,当您对其进行初始化时,您将分配一个初始化为 source.array_capacity 值的 double。请注意下面一行中使用的括号。

arrayPointer = new double(source.array_capacity);

这肯定会导致在复制过程中发生未定义的行为,因为您最终会访问数组边界之外的元素。上面一行出现在你的复制构造函数和复制赋值运算符中,应该使用方括号代替,如下所示:

arrayPointer = new double[source.array_capacity];

您也永远不会检查 myListsource 实例中是否存储了任何元素。在这种情况下,您应该将 nullptr(或 C++03 中的 NULL)分配给 arrayPointer

作为旁注,您实际上不需要在析构函数中将 NULL 分配给 arrayPointer。一旦对象被销毁,它就消失了,任何事后访问它的尝试都将导致未定义的行为。

关于c++ - 复制构造函数和重载赋值运算符的堆损坏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27350155/

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