How should a multi-threaded C application handle a failed malloc()?

Posted by user294463 on Stack Overflow See other posts from Stack Overflow or by user294463
Published on 2010-05-14T11:28:47Z Indexed on 2010/05/14 11:34 UTC
Read the original article Hit count: 131

Filed under:
|
|

A part of an application I'm working on is a simple pthread-based server that communicates over a TCP/IP socket. I am writing it in C because it's going to be running in a memory constrained environment. My question is: what should the program do if one of the threads encounters a malloc() that returns NULL? Possibilities I've come up with so far:

  1. No special handling. Let malloc() return NULL and let it be dereferenced so that the whole thing segfaults.
  2. Exit immediately on a failed malloc(), by calling abort() or exit(-1). Assume that the environment will clean everything up.
  3. Jump out of the main event loop and attempt to pthread_join() all the threads, then shut down.

The first option is obviously the easiest, but seems very wrong. The second one also seems wrong since I don't know exactly what will happen. The third option seems tempting except for two issues: first, all of the threads need not be joined back to the main thread under normal circumstances and second, in order to complete the thread execution, most of the remaining threads will have to call malloc() again anyway.

What shall I do?

© Stack Overflow or respective owner

Related posts about c

    Related posts about pthreads