【问题标题】:Why do I get an error when the pointer is not copied?为什么不复制指针时会出错?
【发布时间】:2014-08-01 01:01:35
【问题描述】:

以下代码会引发错误。错误在 delete[] pIntArray 错误是 _ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));:

#include <iostream>

using std::cout;
using std::endl;


int main()
{

    int* pIntArray = new int[50];
    cout << "adding numbers to array ..." << endl;

    for (int i = 0; i < 50; i++)
    {
        pIntArray[i] = i + 10;
    }

    cout << "values in array: " << endl;

    for (int i = 0; i < 50; ++i)
    {
        cout << "integer[" << i << "] = " << *(pIntArray++) << endl;

    }

    cout << "deleting dynamic memory ..." << endl;

    delete[] pIntArray;

    cout << "memory deleted." << endl;

    return 0;
}

但事实并非如此。唯一的区别是我正在复制指针并递增副本:

#include <iostream>

using std::cout;
using std::endl;


int main()
{

    int* pIntArray = new int[50];
    cout << "adding numbers to array ..." << endl;
    int* pCopy = pIntArray;

    for (int i = 0; i < 50; i++)
    {
        pIntArray[i] = i + 10;
    }

    cout << "values in array: " << endl;

    for (int i = 0; i < 50; ++i)
    {
        cout << "integer[" << i << "] = " << *(pCopy++) << endl;

    }

    cout << "deleting dynamic memory ..." << endl;

    delete[] pIntArray;

    cout << "memory deleted." << endl;

    return 0;
}

有人能解释一下原因吗?提前致谢。

【问题讨论】:

  • 你给delete[]的指针必须与你从new[]得到的指针相匹配。在这种情况下,您在两者之间增加了它。这也适用于普通的new/deletemalloc/free。你的第二个例子是正确的。

标签: c++ c++11


【解决方案1】:

因为你正在改变指针的值,所以指针指向的内存地址:

示例 1:

[0][0][0][0][0][0][0][0][0][0][0][0]
                                  ^
                                  |
                                  pIntArray is here

示例 2:

[0][0][0][0][0][0][0][0][0][0][0][0]
 ^                                ^
 |                                |
 pIntArray is here                pCopy is here

您需要delete[] 确切的指针(这是因为大多数 C/C++ 运行时存储在ptr - 1 word 分配的内存大小)

【讨论】:

    【解决方案2】:
    for (int i = 0; i < 50; ++i)
    {
        cout << "integer[" << i << "] = " << *(pIntArray++) << endl;
    
    }
    
    cout << "deleting dynamic memory ..." << endl;
    
    delete[] pIntArray;
    

    您使用++ 修改pIntArray 的值,然后将修改后的 值传递给delete[]。您需要将new[] 返回的值准确地传递给delete[]

    【讨论】:

    • 我倾向于这就是原因,但有两个简单的问题:1.这仅与从 new 返回的指针有关吗? 2. 那么,作为一个规则,如果您要更改 new 返回的指针的地址,您是否需要始终先缓存它以便正确删除它?
    • 您需要始终先缓存它吗?我不这么认为,但是如果您像在这个问题中那样将指针用作数组,那么您可能必须将指针取消引用到它的初始值。否则,如果您将指针用作指针而不是数组,则指针指向的当前元素将被删除以避免内存泄漏。每当您使用指针指向另一个新值时,该指针指向的旧值及其内存位置将不复存在,因为您已释放该内存位置。
    猜你喜欢
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2018-10-11
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多