2

I've a mixed project with a huge ammount of old C code and some C++ code as a wrapper linked together in a single binary.

The C code uses a mutex to make malloc-memory-management thread safe, the C++ part does not care pthreads. Will the usage of malloc together with new be thread-safe, if these are true:

  • malloc, realloc and free are protected by a mutex.
  • The standard new-operator is used (I think, it's a pthread-enabled version by default, if pthreads are used, right?)
  • Memory allocated by malloc is never freed by delete and vice-versa.
urzeit
  • 2,863
  • 20
  • 36
  • related: http://stackoverflow.com/q/855763/3684343 – mch Feb 27 '15 at 10:22
  • Are you targeting full posix cross-platform compatibility? Or just, say, Linux with gcc? Which C and C++ Standards are you targeting (the answer is trivial with the latest versions, assuming conforming compilers). – BoBTFish Feb 27 '15 at 10:23
  • @BoBTFish: Linux and gcc only – urzeit Feb 27 '15 at 10:24
  • @urzeit Then I believe with `-pthread` you are fine, but I'll let someone else fill in the details/provide references (or contradict me of course). – BoBTFish Feb 27 '15 at 10:24
  • [This](http://man7.org/linux/man-pages/man3/malloc.3.html#NOTES) reports `malloc` is safe, but didn't find a reference that `new` is implemented in terms of `malloc`, although several SO answers state this without a reference. – BoBTFish Feb 27 '15 at 10:58
  • I thought malloc was threadsafe if you #defined something. Can't recall what. – johnnycrash Mar 11 '15 at 20:11

0 Answers0