Re: malloc reentrant?

From: John Reiser (
Date: 07/20/05

Date: Wed, 20 Jul 2005 07:12:02 -0700

> Does anybody if malloc is reentrant? My glibc is version 2.3.2.
> "man signal" states a set of functions that according to the posix
> standard should be reentrant, malloc not among them.

{malloc, calloc, realloc, free, posix_memalign} of glibc-2.2+ are thread
safe. However, they are not async signal safe. They are not reentrant,
and must not be called directly or indirectly from a signal handler:
a crash may result, perhaps much later. The source begins:
  /* Malloc implementation for multiple threads without lock contention.
   Copyright (C) 1996-2002, 2003, 2004 Free Software Foundation, Inc.
   This file is part of the GNU C Library.
   Contributed by Wolfram Gloger <>
   and Doug Lea <>, 2001.
  This is a version (aka ptmalloc2) of malloc/free/realloc written by
  Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.

* Version ptmalloc2-20011215
  $Id: malloc.c,v 1.142 2004/12/11 21:14:40 drepper Exp $
  based on:
  VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
The source does contain calls to {mutex_lock, mutex_unlock}.

A significant consequence is that a signal handler that uses {printf,
fprintf} should employ {setbuf, setbuffer, setlinebuf, setvbuf} before
enabling receipt of the signal. Otherwise {printf, fprintf} may call
malloc to allocate a buffer, which can lead to trouble. POSIX does not
require {printf, fprintf} to be async signal safe, and glibc-2.* generally
has adopted a strategy of minimal conformance. But so far in practice,
deciding buffering in advance has been enough to make printf usable from
commmon signal handlers.