How should a multi-threaded C application handle a failed malloc()?
- by user294463
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:
No special handling. Let malloc() return NULL and let it be dereferenced so that the whole thing segfaults.
Exit immediately on a failed malloc(), by calling abort() or exit(-1). Assume that the environment will clean everything up.
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?