RE: Are g_try_malloc() and g_free() thread-safe?

g_mem_set_vtable() doesn't really help (at least right now) because I
can't get any definitive information on whether malloc() and free() are
thread-safe.  I am building with -D_REENTRANT so the thread-safe
versions of malloc() and free() should be already/automatically
implemented.  Somewhere I read that the reentrant versions of malloc(),
calloc(), and realloc() lock the heap but free() does not resulting in
possible heap corruption.  That really doesn't make sense to me (that is
locking during allocation but not release) and I wasn't sure with what
authority the person made those claims.  It would however, explain my
problem.  Any thoughts?


It is documented that g_malloc() indeed aborts during failure.  This is
infact why I am using g_try_malloc() instead.  The information for the
documentation of g_try_malloc() states:

"Attempts to allocate n_bytes, and returns NULL on failure. Contrast
with g_malloc(), which aborts the program on failure."

-----Original Message-----
From: gtk-list-bounces gnome org [mailto:gtk-list-bounces gnome org] On
Behalf Of Ben Johnson
Sent: Monday, February 07, 2005 11:30 PM
To: gtk-list gnome org
Subject: Re: Are g_try_malloc() and g_free() thread-safe?

I was given and found some answers to my questions.  thought I'd share
for the good of the curious.

On Mon, Feb 07, 2005 at 03:41:42PM -0800, Ben Johnson wrote:
> how do you remove the risk?  you have to compile libc with _REENTRANT?

g_malloc(), g_free(), and associated functions are wrappers for the libc
malloc() and free().  I'm told that when the program is linked against a
thread library (not sure which thread lib... maybe all of them?) there's
some symbol magic that happens and thread safe versions of these
functions in the thread library are called instead.  (I'm paraphrasing,
so this may not be entirely accurate... or may be in need of serious
correction, but that's my understanding.)

> Also, the g_mem_set_vtable() function does not appear to be thread

if g_mem_set_vtable() is used, it MUST be called BEFORE any other glib
function, so this is a non-issue.

BTW, I also found out that g_malloc() (and therefore all glib functions
that use g_malloc()) will call abort() if the wrapped malloc() fails.
Does everyone know that?  I was surprised to find out.  I think this
tidbit could use a little more publicity than the blurb in the glib docs
about g_try_malloc().

- Ben

gtk-list mailing list
gtk-list gnome org

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]