[英]Why does this program compiles ? Should it not give an error as I am deleting the same thing twice
This code runs perfectly fine and does not give any error which I think it should as I am deleting the same thing twice.这段代码运行得很好,没有给出任何我认为应该的错误,因为我删除了同样的东西两次。
#include<iostream>
int main(){
int* var1 = new int;
int* var2 = var1;
*var1 = 10;
*var2 = 15;
std::cout << var1 << std::endl;
std::cout<<var2<<std::endl;
delete var1;
delete var2;
std::cout<<"Hello World";
return 0;}
The variables var1
and var2
are stack variables, but the addresses they hold are not.变量
var1
和var2
是堆栈变量,但它们保存的地址不是。 The address that a pointer holds might point to garbage, to the stack, to the heap or to the data segment.指针持有的地址可能指向垃圾、堆栈、堆或数据段。 Neither would be automatically deleted when the pointer is dead.
当指针失效时,两者都不会自动删除。
In your first post of the code it seemed that you assume a local pointer variable is dead, by getting out of scope and frees the address that it holds.在你的第一篇代码中,你似乎假设一个局部指针变量已经死了,通过离开 scope 并释放它持有的地址。 This is not the case.
不是这种情况。 This is why heap allocation requires manual freeing.
这就是堆分配需要手动释放的原因。
But then you posted the edit with two calls to delete
.但是随后您通过两次调用
delete
发布了编辑。
In your program, var1
and var2
point to the same place on the heap, which is perfectly fine.在您的程序中,
var1
和var2
指向堆上的同一个位置,这非常好。
Then their content is populated with different values, which is also ok.然后用不同的值填充它们的内容,这也可以。 Each assignment overrides the previous as it is written to the same place in memory.
每个分配都会覆盖之前的分配,因为它被写入 memory 中的相同位置。
As for the two calls to delete
on the same address, the compiler doesn't follow what your code does.至于在同一地址上对
delete
的两次调用,编译器不会按照您的代码执行操作。 It only compiles the code and checks for specific errors that the specification required it to check.它只编译代码并检查规范要求它检查的特定错误。
The compiler in most cases cannot actually notice if an address is deleted twice, so it would probably not even try to give a warning, even if you delete the exact same variable twice, consequently.在大多数情况下,编译器实际上不会注意到一个地址是否被删除了两次,因此它可能甚至不会尝试发出警告,即使您删除了完全相同的变量两次,因此也是如此。 For example, both gcc and clang doesn't raise any warning for the following code, which is fine, they are not supposed to:
例如, gcc 和 clang都不会对以下代码发出任何警告,这很好,它们不应该:
int main() {
int* ptr = new int;
delete ptr;
delete ptr;
}
Static analysis tools may analyze this and point at the problematic code, but it is not the job of the compiler. Static 分析工具可能会对此进行分析并指出有问题的代码,但这不是编译器的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.