You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 13 Next »

Functions should provide consistent and usable error checking mechanism. Complex interfaces are sometimes ignored by programmers, resulting in code that is not error checked. Inconsistent interfaces are frequently misused and difficult to use, resulting in lower quality code and higher development costs.

Noncompliant Code Example (strlcpy())

The strlcpy() function copies a null-terminated source string to a destination array. It is designed to be safer, more consistent, and less error prone replacements for strcpy().

The strlcpy() function returns the total length of the string it tried to create (the length of the source string).

To detect truncation, perhaps while building a pathname, something like the following might be used:

char *dir, *file, pname[MAXPATHLEN];

/* ... */

if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname)) {
  /* handle source string too long error */
}

Compliant Solution (strcpy_m())

The managed string library [Burch 2006] handles errors by consistently returning the status code in the function return value. This approach encourages status checking because the user can insert the function call as the expression in an if statement and take appropriate action on failure.

The strcpy_m() function is an example of a managed string function that copies a source managed string into a destination managed string.

errno_t retValue; 
string_m dest, source;  

/* ... */

if (retValue = strcpy_m(dest, source)) { 
  fprintf(stderr, "Error %d from strcreate_m.\n", retValue);
} 

The greatest disadvantage of this approach is that it prevents functions from returning any other value. This means that all values (other than the status) returned by a function must be returned as a pass-by-reference parameter, preventing a programmer from nesting function calls. This tradeoff is necessary because nesting function calls can conflict with a programmer's willingness to check status codes.

Risk Assessment

Failure to do so can result in type errors in the program.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

API04-C

medium

unlikely

medium

P4

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

CERT C++ Secure Coding Standard: API04-CPP. Provide a consistent and usable error checking mechanism

ISO/IEC 9945:2003

ISO/IEC 9899:1999 Section 7.21, "String handling <string.h>"

ISO/IEC 23360-1:2006

ISO/IEC TR 24731-1:2007

ISO/IEC PDTR 24731-2

MISRA Rule 20.4

MITRE CWE: CWE-754: Improper Check for Unusual or Exceptional Conditions

Bibliography

[Burch 2006]
[CERT 2006c]
[Miller 1999]
[Seacord 2005a] Chapter 2, "Strings"


      13. Application Programming Interfaces (API)      

  • No labels