为什么删除[]应该崩溃? [英] Why delete[] should crash?
本文介绍了为什么删除[]应该崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int _tmain(int argc, _TCHAR* argv[])
{
int *c= new int[5];
c[0] = 100;
c[1] = 200;
c[2] = 300;
c[3] = 400;
c[4] = 500;
int i=0;
while(i<5)
{
printf("%d\n",*c++);
i++;
}
delete[] c;
return 0;
}
为什么当我删除指针时它断言使用堆块? :confused:
why it asserts Heap-Block-in-use when I delete the pointer? :confused:
推荐答案
当你执行while循环时,你增加c指针,所以最后不再指向最初分配的分配。
你必须在循环中使用临时变量;
When you do your while loop, you increment c pointer so at the end is not pointing to the originally allocated allocation anymore.
You have to use a temporary variable Inside the loop;
...
int i=0;
int *t = c;
while(i<5)
{
printf("%d\n",*t++);
i++;
}
...
非常感谢。
如何跟踪这个指针将运行到内存中的这些元素?
例如假设我有一个类似下面的函数
Thanks a lot.
How does it keep track that this pointer will run to these many elements in memory?
For example assume I have a function like below
int* supplyPtr()
{
int* pSet = new int[10];
return ++pSet;
}
void main()
{
int* p = supplyPtr();
delete[] p;
}
在上面的示例中,当我从pSet返回pSet时,它如何跟踪p?
supplyPtr,它干净地删除了内存。
但是如果我传递++ pSet,它会断言。它如何关联指针及其在内存中的元素数量?你能解释一下吗?或者指向正确的资源?
In the above sample how does it keep track of p?
when I return pSet from the supplyPtr, it cleanly deletes the memory.
But if I pass ++pSet, it asserts. How does it associate a pointer and it''s number of elements in memory? Could you please explain? or point me to the right resource?
这篇关于为什么删除[]应该崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文