Why can't malloc be used in signal handlers? What can "happen wrong"?
+4
A:
A signal handler can be called at any time, including during times when another call to malloc
is in progress. If this happens, one of two things will occur:
- Your process will deadlock inside the signal handler, because
malloc
will be unable to acquire the heap lock. - Your process will corrupt its heap, because
malloc
does acquire the lock (or doesn't think it needs it), then proceeds to modify render the heap inconsistent, leading to a later crash.
JSBangs
2010-07-29 19:46:54
Interesting. But can you explain why this cannot happen during normal thread context switching? The heap is also shared among all threads in a process. Is malloc() not pre-emptable except during signal handler invocation?
Amardeep
2010-07-29 19:59:02