内存泄漏是“未定义的行为"吗?C++中的类问题?

事实证明,在 C++ 中,许多看起来很无辜的东西是未定义的行为.例如,一旦一个非空指针被delete甚至打印出该指针值是未定义的行为.

Turns out many innocently looking things are undefined behavior in C++. For example, once a non-null pointer has been delete'd even printing out that pointer value is undefined behavior.

现在内存泄漏肯定很糟糕.但它们是什么阶级情况――定义的、未定义的或其他什么类别的行为?

Now memory leaks are definitely bad. But what class situation are they - defined, undefined or what other class of behavior?

推荐答案

内存泄漏.

没有未定义的行为.泄漏内存是完全合法的.

Memory leaks.

There is no undefined behavior. It is perfectly legal to leak memory.

未定义行为:是标准特别不想定义的操作,由实现决定,以便在不违反标准的情况下灵活地执行某些类型的优化.

Undefined behavior: is actions the standard specifically does not want to define and leaves upto the implementation so that it is flexible to perform certain types of optimizations without breaking the standard.

内存管理定义明确.
如果您动态分配内存并且不释放它.然后,内存仍然是应用程序的属性,可以按照它认为合适的方式进行管理.您丢失了对那部分内存的所有引用这一事实既不存在也不存在.

Memory management is well defined.
If you dynamically allocate memory and don't release it. Then the memory remains the property of the application to manage as it sees fit. The fact that you have lost all references to that portion of memory is neither here nor there.

当然,如果您继续泄漏,那么您最终将耗尽可用内存并且应用程序将开始抛出 bad_alloc 异常.但这是另一个问题.

Of course if you continue to leak then you will eventually run out of available memory and the application will start to throw bad_alloc exceptions. But that is another issue.

相关文章