当我们通过New分配而通过free解除分配时会发生什么 [英] What happens when we allocate through New and deallocate through free

查看:197
本文介绍了当我们通过New分配而通过free解除分配时会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们通过New分配而通过free分配时会发生什么.
虽然它是非法使用,但我们将导致服务器崩溃.
我只想知道步骤/过程如何导致服务器崩溃

What happens when we allocate through New and deallocate through free.
Though its illegal to use and we will get a server crash.
I just want to know how the steps/process leads to server crash

推荐答案

对于普通的基本类型(int,float等),我认为没有什么太重要的了应该会发生.

对于类(和结构),它将不会调用类析构函数,并且不会释放该类分配的所有内存(如果在析构函数中正确完成),并且如果在析构函数中实现,则可能不会调用某些清理代码. />
如果是这种情况,那么服务器"可能会在执行过程中泄漏内存,并且在耗尽系统上所有内存时都会崩溃.
For normal basic types (int, float, ...) I would assume nothing too important should happen.

For classes (and structs) it will not call the class destructor, and all memory allocated by the class will not be released (if done properly in the destructor) and some clean up code might not be called if implemented in the destructor.

If this is your case, then the "server" will probably leak memory during it execution and will crash if it comes to a point where it consumes all the memory on the system.


不要这样做!如果您确实具有通过这种方式管理内存分配的代码,那么您将面临麻烦,甚至可能失业.
Don''t do it! If you do have code that manages memory allocation this way then you are heading for trouble, and probably unemployment.


这是一个好问题.

就像Maximilien所说的那样,您将通过调用free来删除与所使用的指针直接相关的内存,但是,如果指针指向一个对象,则不会调用析构函数,而释放在析构函数内部的内存.会导致泄漏.

服务器崩溃最可能的原因是在调用new时使用的运行时库在下面使用了与您对 free 的调用不匹配的其他内存分配函数. .

两个例子是
1)如果新功能是使用Windows API调用 :: HeapAlloc 实现的.
2)如果new使用 :: malloc 从不同于您正在链接的库中的C运行时库中分配内存,以调用 free .

您应该始终为每个分配调用匹配的释放"存储方法.
您可以在代码中混合使用malloc/free和new/delete分配,但是,每个分配的缓冲区的内存管理必须使用匹配的释放功能.
This is a good question.

Like Maximilien said, you will delete the memory directly associated with the pointer you are using with the call to free, however, if the pointer is to an object, the destructor will not be called, and the memory inside of the destructor that is released will cause a leak.

The most likely cause of a crash in your server, is the run-time library that is used in your call to new, is using a different memory allocation function underneath that is not matched to your call to free.

Two examples would be,
1) If new was implemented using the Windows API call ::HeapAlloc.
2) If new uses ::malloc to allocate memory from a different C run-time library than the library you are linking in for the call to free.

You should always call the matching "release" memory method with each allocation.
You can mix malloc/free and new/delete allocations in your code, however, the memory management for each allocated buffer must use the matching release function.


这篇关于当我们通过New分配而通过free解除分配时会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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