Sungju's Slow Life

Personal journal


Are malloc() and free() functions thread-safe?

Recently, someone asked me why he can’t allocated enough memory with a lot of thread functions.

At first, I just tried to explain that there is no problem in Linux kernel or malloc() functions. But, when double checked his code, I found that he used malloc() without any safeguard. Yeah, no synchronization around malloc(). Sigh.

malloc() and free() functions are use static data structures which can cause the synchronization problem in multi-threaded application. They are not thread-safe. You will be better to make your own function to allocate and deallocate for memory and put some synchronization code into that functions. That will be helpful.

There are some web documents that talk about malloc() and free(). One of them is this: http://www.ibm.com/developerworks/linux/library/l-reent.html

Additional Note: In RHEL products, they use ptmalloc() which is thread-safe version of malloc(). So, it does not make any problem within thread application by itself.



Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Me

A software engineer who loves any technologies that makes life easier. That’s why I love Linux and Mac at the same time.

Newsletter

%d bloggers like this: