删除指向堆的指针时程序崩溃? [英] Program crashes when deleting a pointer pointing to the heap?

查看:116
本文介绍了删除指向堆的指针时程序崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我去...

int *foo = new int;  
foo += 1; 
delete foo;    

大多数时间崩溃。有什么原因吗?我想让指针指向一个点(4字节)。谢谢。

Most of the time it crashes. Is there a reason for this? I'm trying to have the pointer point one spot forward (4 bytes). Thanks.

编辑(六个月后):这是我问的第一个问题,这是一个愚蠢的问题,应该得到的downvote。如果它对学习者没有用处,它可以被删除。我确实是说在堆上分配一个int的四个字节,然后移动指针四个字节前进,然后删除int指针,基本上删除上帝知道什么,导致未定义的行为。谢谢你的帮助。

Edit (six months later): This was the first question I asked on SO, and it was a silly question and deserved the downvotes. It can be deleted if it's of no use to learners. I was indeed talking about allocating an int of four bytes on the heap, then moving the pointer four bytes forward, and then deleting the int pointer, essentially deleting God knows what, leading to undefined behaviour. Thanks for your help.

推荐答案

您必须传递 delete c> new 。你不这样做。

You must pass to delete the value that new returned. You don't do that.

我认为你对你传递给 delete 感到困惑。我认为你相信 delete foo 将删除与变量相关的内存。它不。它删除其地址存储在 foo 中的内存。

I think that you are confused as to what you are passing to delete. I think that you believe that delete foo will delete the memory associated with the variable. It doesn't. It deletes the memory whose address is stored in foo.

例如,这是合法的:

int* foo = new int;
int* bar = foo;
delete bar;

重要的不是变量的名称,而是变量的值。

What matters is not the name of the variable, but rather the value of the variable.

这是另一个例子:

int* arr = new int[10];
int* ptr = arr;
for (int i; i < 10; i++)
{
    *ptr = i;
    ptr++;
}
delete[] arr;

为了执行指针算术,并保留 new [ ] ,我们引入了一个额外的变量。我使用一个数组,因为对指向单个值的指针执行算术没有意义。

In order to perform pointer arithmetic, and retain the address returned by new[], we introduced an extra variable. I used an array because it doesn't make sense to perform arithmetic on a pointer to a single value.

请注意,在上面的代码中,可以使用 arr [i] = i 避免需要第二个指针变量。我写了它如上所示,说明当指针算术是正确的选项时你如何编码。

Note that in the code above, it could be written more clearly using arr[i] = i and so avoid the need for a second pointer variable. I wrote it as above to illustrate how you might code when pointer arithmetic is the right option.

这篇关于删除指向堆的指针时程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆