Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glib memory allocation VS std *alloc and free

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.

like image 712
Manuel Salvadores Avatar asked Oct 28 '10 09:10

Manuel Salvadores


2 Answers

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.

like image 74
ptomato Avatar answered Oct 20 '22 14:10

ptomato


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.

like image 42
Prof. Falken Avatar answered Oct 20 '22 12:10

Prof. Falken