Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added Rose compliance section

...

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.

...

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.

...

The tool Compass Rose is able to detect violations of this rule. In particular, Rose ensures that any pointer returned by malloc(), calloe(), or realloc() is first checked for NULL before otherwise used (or else it is {{free()}}d. Rose doesn't handle cases where an allocation is assigned to an lvalue that is not a variable (such as a struct member or C++ function call returning a reference.)

The Coverity Prevent CHECKED_RETURN, NULL_RETURNS, and REVERSE_INULL checkers can all find violations of this rule. The CHECKED_RETURN finds instances where a pointer is checked against NULL and then later dereferenced. The NULL_RETURNS checker identifies functions that can return a null pointer but are not checked. The REVERSE_INULL identifies code that dereferences a pointer and then checks the pointer against NULL. Coverity Prevent cannot discover all violations of this rule, so further verification is necessary.

...