算术运算后删除指针 [英] Delete a pointer after the arithmetics
问题描述
int main() {
int* i = new int(1);
i++;
*i=1;
delete i;
}
这是我的逻辑:
I将I递增1,然后为其分配一个值。然后删除I,以便在泄漏原始内存的同时释放内存位置。我的问题在哪里?
I increment I by 1, and then assign a value to it. Then I delete the I, so I free the memory location while leaking the original memory. Where is my problem?
我还尝试了其他版本。每次,只要我做算术并删除指针,我的程序就会崩溃。
I also tried different versions. Every time, as long as I do the arithmetics and delete the pointer, my program crashes.
推荐答案
您的程序显示的内容有几个行为未定义的情况:
What your program shows is several cases of undefined behaviour:
- 您写入未分配的内存(
* i = 1
) - 释放未分配的内容,实际上是
删除i + 1
。
- You write to memory that hasn't been allocated (
*i = 1
) - You free something that you didn't allocate, effectively
delete i + 1
.
您必须调用 delete
,其指针值与从<$返回的指针值完全相同c $ c> new -没有别的。假设其余代码有效,则在 int * i = new int(1)之后执行
,然后 int * j = i;
; 删除j;
。 [例如, int * i = new int [2];
将使您的 i ++; * i = 1;
有效代码]
You MUST call delete
on exactly the same pointer-value that you got back from new
- nothing else. Assuming the rest of your code was valid, it would be fine to do int *j = i;
after int *i = new int(1);
, and then delete j;
. [For example int *i = new int[2];
would then make your i++; *i=1;
valid code]
这篇关于算术运算后删除指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!