Versions Compared

Key

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

...

Upon failure, the malloc() function returns NULL. Failing to detect and properly handle this error condition appropriately can lead to abnormal and abrupt program termination.

Code Block
bgColor#ccccff
/* ... */
size_t size = strlen(input_string);
if (size == SIZE_MAX) {
  /* Handle Error */
}
str = malloc(size+1);
if (str == NULL) {
  /* Handle Allocation Error */
}
strcpy(str, input_string);
/* ... */
free(str);

Non-Compliant Code Example (File Operations)

In this example, fopen() is used to open a file for reading. If fopen() is unable to open the file it returns a NULL pointer. Failing to detect and properly handle this error condition appropriately can lead to abnormal and abrupt program termination.

Code Block
bgColor#FFcccc

FILE fptr = fopen("MyFile.txt","r");

Compliant Solution (File Operations)

To correct this example, the return value of fopen() should be checked for NULL.

Code Block
bgColor#ccccff

FILE fptr = fopen("MyFile.txt","r");
if (fptr == NULL) { 
   /* Handle error condition */
}

Wiki Markup
This example also applies to rule \[[FIO32-C. Detect and handle file operation errors]\].

References

Failing to detect error condition can result in unexpected program behavior, and possibly abnormal program termination resulting in a denial-of-service condition.

...