Versions Compared

Key

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

...

In this example, input_str is copied into dynamically allocated memory referenced by str. If malloc() fails, it returns a null pointer that is assigned to str. When str is dereferenced in memcpy(), the program behaves in an unpredictable manner.

Code Block
bgColor#FFCCCC
/* ... */
size_t size = strlen(input_str)+1;
str = (char*) malloc(size);
memcpy(str, input_str, size);
/* ... */
free(str);
str = NULL; 

In accordance with rule MEM35-C. Allocate sufficient memory for an object, the argument supplied to malloc() is checked to ensure a numeric overflow does not occur. In most cases it is preferable to check that this value does not exceed some maximum allocation that is typically much smaller than SIZE_MAX.

...

To correct this error, ensure the pointer returned by malloc() is not null. This also ensures compliance with MEM32-C. Detect and handle memory allocation errors.

Code Block
bgColor#ccccff

/* ... */
size_t size = strlen(input_str)+1;
str = (char*) malloc(size);
if (str == NULL) {
  /* Handle Allocation Error */
}
memcpy(str, input_str, size);
/* ... */
free(str);
str = NULL; 

Risk Assessment

Wiki Markup
Dereferencing a null pointer results in undefined behavior, typically abnormal program termination.  In some situations, however, dereferencing a null pointer can lead to the execution of arbitrary code \[[Jack 07|AA. C References#Jack 07], [van Sprundel 06|AA. C References#van Sprundel 06]\].  The indicated severity is for this more severe case; on platforms where it is not possible to exploit a null pointer dereference to execute arbitrary code, the actual severity is low.

...