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?
The only standard that speaks about this is C11 (since there was no notion of multithreading before), which says (7.22.3/2):
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
ptmalloc2I think), and it’s basically always been fine. [Update, thanks to @ArjunShankar: Posix does indeed require thatmallocbe thread-safe.](Note, though, that other implementations such as Google’s
tcmallocmay have better performance in multithreaded applications.)(For C++, see C++11: 18.6.1.4.)