Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual C++ thread safety of free and malloc?

Does anyone know if free and malloc are threadsafe on visual C++ 2010?

I have having bizarre problems where memory is getting corrupted and im pretty much down to this being the only possiblity.

Does anyone know if the safety can be turned on and off and how?

like image 677
myforwik Avatar asked Jan 28 '11 09:01

myforwik


People also ask

Is malloc thread-safe C?

Some functions are inherently thread-safe, for example memcpy() . Some functions, such as malloc() , can be made thread-safe by implementing the _mutex_ * functions.

Is free () thread-safe?

By default, new/delete are often not thread safe in a FreeRTOS app because the basic malloc and free are not thread safe. Some embedded libraries have hooks that can be defined to make these functions thread safe.

Is malloc thread-safe on Windows?

Provided you're linking with thread-safe libraries and using the correct flags, yes, malloc should be thread-safe. If you think otherwise, you should post some code for us to examine. I should mention that, in the vast majority of cases, it's never the libraries (which have been tested by uncounted millions of people).

Is malloc shared among threads?

No, because you still call malloc multiple times (once per thread), and each call must return a distinct allocation.


1 Answers

Provided you're linking with thread-safe libraries and using the correct flags, yes, malloc should be thread-safe.

If you think otherwise, you should post some code for us to examine.

I should mention that, in the vast majority of cases, it's never the libraries (which have been tested by uncounted millions of people). It's almost always your own code which, if you're thorough, has been tested by at most several dozen :-)

Not to say Microsoft (or any other large software house) doesn't ship bugs, just that they'd be discovered and fixed pretty damn quick.

like image 91
paxdiablo Avatar answered Sep 26 '22 22:09

paxdiablo