错误原因:未分配要释放的指针

时间:2019-04-07 06:05:39

标签: c++ pointers delete-operator

string tableName = "test2";
var batch = new TableBatchOperation();
CloudStorageAccount storageAccount = 
CreateStorageAccountFromConnectionString(storageConnectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new 
TableClientConfiguration());
CloudTable table = tableClient.GetTableReference(tableName);
CustomerEntityTwo test = new CustomerEntityTwo("test", "bob")
{
  number= "119"

};
batch.InsertOrMerge(test);
table.ExecuteBatch(batch);

错误:malloc:***对象0x7ffdff400630错误:未分配指针。 但是,如果我不#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; } ,它会起作用。

2 个答案:

答案 0 :(得分:4)

使用时

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;

答案 1 :(得分:1)

int* temp = a;

您复制了指针,因此atemp指向同一事物, 然后在

delete a;

您删除了a,因此temp变成了一个悬空指针,取消引用它会导致未定义的行为。

理想情况下应该这样做

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