且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用_freea真的有必要吗?

更新时间:2023-10-26 19:11:40

每次调用_malloca之后都调用_freea总是很重要.

It is always important to call _freea after every call to _malloca.

_malloca类似于_alloca,但是增加了一些额外的安全检查和增强功能以​​保护您.结果,_malloca可以在堆而不是堆栈上进行分配.如果发生这种情况,并且您不调用_freea,则会发生内存泄漏.

_malloca is like _alloca, but adds some extra security checks and enhancements for your protection. As a result, it's possible for _malloca to allocate on the heap instead of the stack. If this happens, and you do not call _freea, you will get a memory leak.

在调试模式下,_malloca总是在堆上分配,因此也应释放.

In debug mode, _malloca ALWAYS allocates on the heap, so also should be freed.

搜索_ALLOCA_S_THRESHOLD以了解有关阈值如何工作以及_malloca代替_alloca的原因的详细信息,

Search for _ALLOCA_S_THRESHOLD for details on how the thresholds work, and why _malloca exists instead of _alloca, and it should make sense.

有评论表明该人只是在堆上分配,并使用智能指针等.

There have been comments suggesting that the person just allocate on the heap, and use smart pointers, etc.

堆栈分配有很多优点,_malloca将为您提供堆栈分配,因此有很多理由希望这样做. _alloca将以相同的方式工作,但是很可能导致堆栈溢出或其他问题,不幸的是,它没有提供很好的异常,而是倾向于破坏您的进程. _malloca在这方面更加安全,并且可以保护您,但是代价是您仍然需要使用_freea释放内存,因为_malloca可能(但不太可能在释放模式下)选择在堆上而不是堆栈上进行分配.

There are advantages to stack allocations, which _malloca will provide you, so there are reasons for wanting to do this. _alloca will work the same way, but is much more likely to cause a stack overflow or other problem, and unfortunately does not provide nice exceptions, but rather tends to just tear down your process. _malloca is much safer in this regard, and protects you, but the cost is that you still need to free your memory with _freea since it's possible (but unlikely in release mode) that _malloca will choose to allocate on the heap instead of the stack.

如果您唯一的目标是避免释放内存,那么我建议您使用一个智能指针,该指针将在成员超出范围时为您处理内存的释放.这样可以在堆上分配内存,但是很安全,并且可以避免释放内存.不过,这仅在C ++中有效-如果您使用的是普通C语言,则此方法将无效.

If your only goal is to avoid having to free memory, I would recommend using a smart pointer that will handle the freeing of memory for you as the member goes out of scope. This would assign memory on the heap, but be safe, and prevent you from having to free the memory. This will only work in C++, though - if you're using plain ol' C, this approach will not work.

如果您出于其他原因(通常是性能,因为堆栈分配非常非常快)而试图在堆栈上进行分配,我建议您使用_malloca并考虑到需要在值上调用_freea的事实

If you are trying to allocate on the stack for other reasons (typically performance, since stack allocations are very, very fast), I would recommend using _malloca and living with the fact that you'll need to call _freea on your values.