2

I heard "malloc is thread-safe because it provide a synchronization primitive so that simultaneous to malloc will not corrupt the heap".

But when I look at the source code of malloc function in visual studio crt, it turns out that the malloc function just pass the request to syscall HeapAlloc. So I think it is the opearting system itself provide some kind of synchronization to protect application from corrupted heap rather than malloc.

Then what about linux? Does malloc itself provide some kind of synchronization?

Jichao
  • 35,945
  • 40
  • 114
  • 183

1 Answers1

5

The only standard that speaks about this is C11 (since there was no notion of multithreading before), which says (7.22.3/2):

For purposes of determining the existence of a data race, memory allocation functions behave as though they accessed only memory locations accessible through their arguments and not other static dura­tion storage. These functions may, however, visibly modify the storage that they allocate or de­allo­cate. A call to free or realloc that deallocates a region p of memory synchronizes with any allocation call that allocates all or part of the region p. This synchronization occurs after any access of p by the deallocating function, and before any such access by the allocating function.

In short, "it's all fine".

However, specific implementations like Linux will surely have been providing their own, strong guarantees for a long time (since ptmalloc2 I think), and it's basically always been fine. [Update, thanks to @ArjunShankar: Posix does indeed require that malloc be thread-safe.]

(Note, though, that other implementations such as Google's tcmalloc may have better performance in multithreaded applications.)

(For C++, see C++11: 18.6.1.4.)

Kerrek SB
  • 428,875
  • 83
  • 813
  • 1,025
  • 1
    FWIW, at least POSIX specifically requires that all functions specified by the standard, except for a specific list of exceptions, are thread safe. Sources: [Open Group](http://pubs.opengroup.org/onlinepubs/7908799/xsh/threads.html) and the [Linux Man Page](http://linux.die.net/man/7/pthreads). `malloc` is not exempted, and therefore must be thread-safe. – ArjunShankar Oct 09 '12 at 00:56
  • Given that the OP is asking regarding Windows, saying "threading doesn't exist in C" is correct but not too useful. – user541686 Oct 09 '12 at 01:03