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.
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()
is NULL
! Other than that, there's no difference in allocation strategy - g_malloc()
calls malloc()
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()
and free()
, but again, it is possible to change that for debugging purposes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With