glib 内存分配 VS std *alloc 和 free
我倾向于使用 std *alloc/free 函数在我的 C 程序中分配/释放动态内存。 我想知道是否有任何充分理由使用 GLIB 内存分配函数 而不是 std 函数。
如果社区能够指出这些解决方案中的任何一个是赢家/输家的情况,我将不胜感激。我还对使用其中一种可能遇到的性能问题感兴趣。
谢谢 !
编辑至状态平台
这些程序通常运行在所有类型的 Linux/Unix 发行版上,通常是使用 gcc 4.2 编译的 64 位架构。
I tend to use std *alloc/free functions to allocate/free dynamic memory in my C programs.
I wonder if there are any good reasons to use the GLIB Memory Allocation functions instead of the std ones.
I'd be grateful if the comunity could point out situations where either of these solutions is a winner/looser. I am also interested in performance issues that I could hit in case I use one or the other.
Thanks !
Edited to state platforms
These programs normally run on all type of Linux/Unix distributions, normally 64 bits archs compiled using gcc 4.2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在我看来,GLib 函数和标准库函数之间最有价值的区别是,如果分配失败,GLib 函数会中止程序。不再需要检查
malloc()
的返回值是否为NULL
!除此之外,分配策略没有区别 -g_malloc()
在内部调用malloc()
,尽管正如此处的其他答案之一所述,可以更改这一点。另一个区别是 GLib 函数允许您使用 g_mem_profile() 进行(基本的)内存泄漏检查。
GLib还有一个切片分配器,效率更高如果您分配许多相同大小的内存块。这不使用系统
malloc()
和free()
,但同样,可以出于调试目的对其进行更改。In my opinion, the most valuable difference between the GLib functions and the standard library ones is that the GLib functions abort the program if the allocation fails. No more checking to see if the return value from
malloc()
isNULL
! Other than that, there's no difference in allocation strategy -g_malloc()
callsmalloc()
internally, though as one of the other answers here states, it is possible to change that.Another difference is that the GLib functions allow you to have (rudimentary) memory leak checking using
g_mem_profile()
.GLib also has a slice allocator, which is more efficient if you are allocating many equal-sized chunks of memory. This doesn't use the system
malloc()
andfree()
, but again, it is possible to change that for debugging purposes.如果您出于某种原因想要自己控制底层分配策略,可以使用 g_mem_set_vtable() 使用您自己的函数而不是 malloc() / free()。
通过神奇的链接选项,这也可以通过 malloc/free 实现,但是 GLIB 为此公开了一个显式 API,并且可以使用 mem-profiler-table。
If you for some reason want to control the underlying allocation strategy yourself, you can use g_mem_set_vtable() to use your own functions instead of malloc() / free().
This is possible with malloc/free too through magic linking options, but GLIB exposes an explicit API for that, as well the possibility to add your own allocation and free logging with a mem-profiler-table.
取决于底层架构。在 SCO Unix fe 下,malloc 遵循“最适合”策略,即内存优化但速度限制。
因此,如果您的程序依赖于不同系统/平台上的特殊假设,那么控制 malloc 策略总是好的。
depends on the underlying architecture. Under SCO Unix f.e. the malloc follows the "best-fit" strategy, which is memory-optimized but speed-delimitering.
So if your program depends on a special assumption on different systems/platforms it is always good to be in control of the malloc-strategy.