为什么在未复制指针时出现错误?

时间:2014-07-31 16:48:13

标签: c++ c++11

以下代码会引发错误。错误发生在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;
}

有人可以解释一下原因吗?提前谢谢。

2 个答案:

答案 0 :(得分:2)

因为您正在更改指针的值,指针指向的内存中的地址:

示例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分配的内存大小)

答案 1 :(得分:0)

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

}

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

delete[] pIntArray;

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