简体   繁体   English

删除它指向的动态分配的内存后使用指针时没有错误

[英]No error when using pointer after deleting the dynamically allocated memory it points at

I'm learning about dynamic memory in C++.我正在学习 C++ 中的动态内存。 My question is why after removing the variable in the following code I don't get an error?我的问题是为什么在删除以下代码中的变量后我没有收到错误消息?

float* uf = new float(4.26);
delete uf;
cout << uf << '\n';
cout << *uf << '\n';

You don't get an error at compile time , because while the compiler tries to detect straightforward mistakes, it can't possibly know, at any given time, weather or not your pointer points to valid memory or not.您不会在编译时收到错误消息,因为当编译器尝试检测直接错误时,它不可能在任何给定时间知道天气与否,您的指针是否指向有效内存。

You may not get an error at run time , because even though the memory has been "freed", it is still memory.您可能不会在运行时收到错误消息,因为即使内存已被“释放”,它仍然是内存。 It's just not guaranteed to be yours anymore.只是不能保证它不再是你的了。 This is the problem with undefined behavior: it is undefined;这就是未定义行为的问题:它是未定义的; you never know exactly how a problem might manifest itself.你永远不知道问题会如何表现出来。

You mean because it compiles even though it's clearly wrong?你的意思是因为它编译,即使它显然是错误的?

Arguably, in this case the compiler could produce a warning if it really wanted to, but then it's a simplified, unrealistic situation.可以说,在这种情况下,如果编译器真的愿意,它可以产生警告,但这是一种简化的、不切实际的情况。

Consider the following example:考虑以下示例:

float* uf = new float(4.26);
delete uf;
if (random_condition_known_only_at_runtime()) {
    uf = new float(0.0);
}
cout << uf << '\n';
cout << *uf << '\n';

Or:或者:

float* uf = new float(4.26);
if (user_input == 'x') {
    delete uf;
}
cout << uf << '\n';
cout << *uf << '\n';

Or consider concurrency;或者考虑并发; multiple threads may write to the same pointer.多个线程可以写入同一个指针。

The point is that real code will typically depend (directly or indirectly) a lot on I/O operations or other external state like this, making it impossible to know in advance, at compile time, whether the memory pointed to will have been deleted already.关键是实际代码通常(直接或间接)依赖于 I/O 操作或其他类似的外部状态,因此无法在编译时提前知道指向的内存是否已被删除.


Or do you mean because the program doesn't crash?或者你的意思是因为程序没有崩溃? That's because the C++ standard does not prescribe crashes.那是因为 C++ 标准没有规定崩溃。 It instead refers to "undefined behaviour", which means that anything can happen, including random crashes or no effect at all.相反,它指的是“未定义的行为”,这意味着任何事情都可能发生,包括随机崩溃或根本没有影响。 Trying to access memory which was already deleted is a classical example of such undefined behaviour.尝试访问已经被删除的内存是这种未定义行为的典型例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM