Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


This non-compliant code example malloc()}}'s space for a string, copies over a string, and then cleans up the memory. The error lies with the call to the {{free() function inside the signal handler. If an interrupt signal is received during or after the free() call in main(), the heap will be corrupted.


Note: The _Exit() function causes immediate program termination, and is async-safe, whereas exit() calls may call cleanup routines first, and is therefore not async-safe.

Compliant Solution

Signal handlers should be as minimal as possible, only unconditionally setting a flag where appropriate, and returning. They may also call the _Exit() function..

Code Block
#include <signal.h>

char *foo;

void int_handler() {

int main(void) {
  foo = malloc(15);
  if(foo == NULL) {
    /* handle error condition */
    return 0;
  signal(SIGINT, int_handler);
  strcpy(foo, "Hello World.");
  return 0;