Is malloc thread-safe?

69,766

Solution 1

I read somewhere that if you compile with -pthread, malloc becomes thread safe. I´m pretty sure its implementation dependant though, since malloc is ANSI C and threads are not.

If we are talking gcc:

Compile and link with -pthread and malloc() will be thread-safe, on x86 and AMD64.

http://groups.google.com/group/comp.lang.c.moderated/browse_thread/thread/2431a99b9bdcef11/ea800579e40f7fa4

Another opinion, more insightful

{malloc, calloc, realloc, free, posix_memalign} of glibc-2.2+ are thread safe

http://linux.derkeiler.com/Newsgroups/comp.os.linux.development.apps/2005-07/0323.html

Solution 2

Question: "is malloc reentrant"?
Answer: no, it is not. Here is one definition of what makes a routine reentrant.

None of the common versions of malloc allow you to re-enter it (e.g. from a signal handler). Note that a reentrant routine may not use locks, and almost all malloc versions in existence do use locks (which makes them thread-safe), or global/static variables (which makes them thread-unsafe and non-reentrant).

All the answers so far answer "is malloc thread-safe?", which is an entirely different question. To that question the answer is it depends on your runtime library, and possibly on the compiler flags you use. On any modern UNIX, you'll get a thread-safe malloc by default. On Windows, use /MT, /MTd, /MD or /MDd flags to get thread-safe runtime library.

Solution 3

This is quite old question and I want to bring freshness according current state of things.

Yes, currently malloc() is thread-safe.

From the GNU C Library Reference Manual of glibc-2.20 [released 2014-09-07]:

void * malloc (size_t size)

Preliminary: MT-Safe | ...

... 1.2.2.1 POSIX Safety Concepts:

... MT-Safe or Thread-Safe functions are safe to call in the presence of other threads. MT, in MT-Safe, stands for Multi Thread.

Being MT-Safe does not imply a function is atomic, nor that it uses any of the memory synchronization mechanisms POSIX exposes to users. It is even possible that calling MT-Safe functions in sequence does not yield an MT-Safe combination. For example, having a thread call two MT-Safe functions one right after the other does not guarantee behavior equivalent to atomic execution of a combination of both functions, since concurrent calls in other threads may interfere in a destructive way.

Whole-program optimizations that could inline functions across library interfaces may expose unsafe reordering, and so performing inlining across the GNU C Library interface is not recommended. The documented MT-Safety status is not guaranteed underwhole-program optimization. However, functions defined in user-visible headers are designed to be safe for inlining.

Solution 4

Yes, under POSIX.1-2008 malloc is thread-safe.

2.9.1 Thread-Safety

All functions defined by this volume of POSIX.1-2008 shall be thread-safe, except that the following functions1 need not be thread-safe.

[ a list of functions that does not contain malloc ]

Solution 5

Here is an excerpt from malloc.c of glibc :

Thread-safety: thread-safe unless NO_THREADS is defined

assuming NO_THREADS is not defined by default, malloc is thread safe at least on linux.

Share:
69,766

Related videos on Youtube

Alphaneo
Author by

Alphaneo

An electrical engineer, who is a programmer by profession

Updated on July 05, 2022

Comments

  • Alphaneo
    Alphaneo almost 2 years

    Is the malloc() function re-entrant?

    • Nathaniel Sharp
      Nathaniel Sharp about 15 years
    • David Thornley
      David Thornley almost 14 years
      Your title and body ask two different things. Re-entrant normally means "can be safely used in a signal handler", while thread-safe normally means "can be safely used in threads". It's easier to have thread-safe than re-entrant.
  • Matthew Flaschen
    Matthew Flaschen about 15 years
    As stated at groups.google.com/group/comp.lang.c.moderated/browse_thread/‌​…, this is not strictly correct. malloc is neither guaranteed to be, nor guaranteed not be, thread-safe. It is implementation-dependent.
  • plankalkul
    plankalkul about 15 years
    Safety is not partial; if an implementation may not be safe, my interpretation is that it is not safe. Poster did not specify a platform; therefore, no guarantee of safety can be given.
  • ChrisW
    ChrisW about 15 years
    Any given implementation either is or isn't safe. To say that an unknown implementation is unsafe is no more true than saying that it is safe. The correct answer is that it's implementation-dependent.
  • plankalkul
    plankalkul about 15 years
    @ChrisW: since the OP did not specify the implementation, and since safety is an absolute condition (it can be broken with only one exception; only one unsafe action can make something "unsafe"), I decided to answer that it was unsafe. The original poster can determine for him/her self what is the correct answer.
  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE over 12 years
    "I read somewhere..." is really not the sort of quality befitting an accepted answer.. ;-)
  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE over 12 years
    Reentrant routines may use locks as long as the lock is reentrant; this necessitates the lock being roughly equivalent to a recursive or error-checking mutex, but with the added stipulation that the single atomic operation that takes the lock must result in the lock structure being in a consistent state for a newly-held lock with a single reference. Of course then you also have to deal with the case where the state protected by the lock has been partially-modified by the interrupted code in the same thread, but nonetheless reentrant locks can be a building block in handling that...
  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE over 12 years
    Any implementation of malloc on any system conforming to any major threads standard (such as POSIX) is thread-safe.
  • Oktalist
    Oktalist over 11 years
    @ChrisW - Russian roulette is safe.
  • chain ro
    chain ro over 9 years
    Whatever he provides the reference links.
  • paulm
    paulm about 8 years
    I believe /MT /MTd /MD etc just means either use release/debug/dynamic or static CRT version, not that malloc is thread safe or not (it actually calls HeapAlloc which has an no serialize optional flag)
  • DIMMSum
    DIMMSum about 8 years
    Note that simply adding -pthreads does not automatically make malloc thread safe. If you call malloc in a signal handler all sorts of crazy nonsense can happen.
  • Oliver Seiler
    Oliver Seiler over 6 years
    malloc is not deemed safe to call from a signal handler; very little is. It may work in some contexts, but not legal or portable AFAIK (see en.cppreference.com/w/c/program/signal, man7.org/linux/man-pages/man7/signal-safety.7.html)
  • S.S. Anne
    S.S. Anne about 5 years
    @PaulSonier Link is broken, link-only answer, not a good combo.
  • wcochran
    wcochran over 2 years
    This is the most relevant answer today. Any modern multithreaded system can safely use malloc().