Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: merged first two NCE

...

The signal handler may also call a handful of functions, including abort(). (See SIG30-C. Call only asynchronous-safe functions within signal handlers for details of functions that can be safely called from within signal handlers.)

Noncompliant Code Example

...

In this noncompliant code example, err_msg is updated to indicate that the SIGINT signal was delivered.

Code Block
bgColor#FFcccc
langc
#include <signal.h>
#include <stdlib.h>
#include <string.h>

char *err_msg;

void handler(int signum) {
  strcpy(err_msg, "SIGINT encountered.");
}

int main(void) {
  enum { MAX_MSG_SIZE = 24 };
  signal(SIGINT, handler);

  err_msg = (char *)malloc(MAX_MSG_SIZE);
  if (err_msg == NULL) {
    /* Handle error condition. */
  }
  strcpy(err_msg, "No errors yet.");

  /* Main code loop */

  return 0;
}

Noncompliant Code Example (volatile with the Wrong Type)

This noncompliant code example declares err_msg to be volatile. However, because the type of the err_msg object is not sig_atomic_t, the behavior of the program is still undefined  The err_msg variable is a character pointer and not a variable of type volatile sig_atomic_t.

Code Block
bgColor#ffcccc#FFcccc
langc
#include <signal.h>
#include <stdlib.h>
#include <string.h>

volatile char *err_msg;

void handler(int signum) {
  strcpy(err_msg, "SIGINT encountered.");
}

int main(void) {
  enum { MAX_MSG_SIZE = 24 };
  signal(SIGINT, handler);

  err_msg = (volatile char *)malloc(MAX_MSG_SIZE);
  if (err_msg == NULL) {
    /* Handle error condition. */
  }
  strcpy(err_msg, "No errors yet.");

  /* Main code loop */

  return 0;
}

 

Compliant Solution (Writing volatile sig_atomic_t)

...