簡體   English   中英

當未復制指針時,為什么會出現錯誤?

[英]Why do I get an error when the pointer is not copied?

以下代碼引發錯誤。 錯誤是在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;
}

有人可以解釋為什么嗎? 提前致謝。

由於您正在更改指針的值,因此指針所指向的內存地址:

范例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的內存大小)

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

}

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

delete[] pIntArray;

++修改pIntArray的值,然后將修改后的值傳遞給delete[] 您需要傳遞給delete[]完全是new[]返回的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM