gpt4 book ai didi

c++ - 为什么在未复制指针时会出现错误?

转载 作者:行者123 更新时间:2023-11-28 02:43:51 24 4
gpt4 key购买 nike

以下代码会引发错误。错误在 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 处分配的内存大小)

关于c++ - 为什么在未复制指针时会出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25064628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com