为什么会出现错误:未分配正在释放的指针

why is the error: Pointer being freed was not allocated

本文关键字:释放 指针 分配 错误 为什么      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int* a = new int;
*a = 5;
int* b = new int;
*b = 6;
int* temp = a;
delete(a);
a = b;
b = temp;
cout << *temp << endl;
delete (temp); // error

return 0;
}

错误:malloc:对象 0x7ffdff400630 的 *** 错误:未分配正在释放的指针。 但是如果我不delete(a),它就会起作用。

当您使用

int* temp = a;

atemp都指向在该行中分配的同一内存

int* a = new int;

当您使用

delete(a);

该内存已解除分配。那时,tempa都在晃来晃去。

通过使用

a = b;
b = temp;

您将a更改为指向有效内存,但现在btemp都悬而未决。

temp的使用

cout << *temp << endl;
delete (temp); // error

不正确。它们都是未定义行为的原因。对于未定义的行为,试图理解发生的事情是没有意义的——任何事情都可能发生。

但是如果我不delete(a),它就可以了。

这是有道理的。如果没有该调用,所有指针将继续有效,直到函数结束。

不过,您应该在函数结束之前添加代码以删除这两个指针。但是,您必须跟踪哪些指针在调用delete时使用有效。

您可以打印它们的值来计算出来。

std::cout << "a: " << (void*)a << std::endl;
std::cout << "b: " << (void*)b << std::endl;
std::cout << "temp: " << (void*)temp << std::endl;

in

int* temp = a;

你复制指针,所以atemp指向同一件事, 然后在

delete a;

您删除atemp使其成为悬而未决的指针,取消引用它会导致未定义的行为。

理想情况下,你应该这样做

temp = null; 

就在delete之后或为了更好地使用现代 CPP 附带的共享指针。

#include <iostream>
#include <memory>
auto main() -> int
{
auto ptr = std::make_shared<int>(5);
std::cout << "ptr value is " << *ptr << std::endl;
auto ptr1 = ptr; // Reference counted copy
std::cout << "ptr value is " << *ptr1 << std::endl;
std::cout << "Total reference count :" << ptr1.use_count() << std::endl;
ptr.reset(); // Resetting  ptr, thus reference count drops to 1
std::cout << "Total reference count :" << ptr1.use_count() << std::endl;;
return 0;
}