Versions Compared

Key

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

Strings must contain a null-termination character at or before the address of the last element of the array before they can be safely passed as arguments to standard string-handling functions, such as strcpy() or strlen(). This is because these functions, as well as other string-handling functions defined by the C standard Standard [ISO/IEC 9899:2011], depend on the existence of a null-termination character to determine the length of a string. Similarly, strings must be null-terminated before iterating on a character array where the termination condition of the loop depends on the existence of a null-termination character within the memory allocated for the string, as in the following example:

...

The standard strncpy() function does not guarantee that the resulting string is null terminated [ISO/IEC 9899:2011]. If no null character is containded contained in the first n characters of the source array, the result could not result cannot be null-terminated.

In the first noncompliant code example, ntbs is null-terminated before the call to strncpy(). However, the subsequent execution of strncpy() can overwrite the null-termination character.

...

The correct solution depends on the programmer's intent. If the intent was is to truncate a string while ensuring that the result remains a null-terminated string, this solution can be used:

...

If the intent is to copy without truncation, this example copies the data and guarantees that the resulting null-terminated byte string is null-terminated. If the string cannot be copied, it is handled as an error condition.

...

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_VLDRA_V

600 S

Fully implemented.

Compass/ROSE

 

 

Can detect some violations of this rule.

Klocwork

Include Page
Klocwork_V
Klocwork_V

NNTS

 

LDRA tool suite

Include Page
LDRA_V
LDRA_V

600 S

Fully implemented.

Related Vulnerabilities

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

Related Guidelines

...

...

TR 17961 (Draft) Passing a non-null-terminated character sequence to a library function that expects a string [strmod]
ISO/IEC TR

...

24731-1:2007Section 6.7.1.4, "The strncpy_s

...

Function"
ISO/IEC TR 24772String termination [CMJ]
MITRE CWE

...

...

Failure to constrain operations within the bounds of an allocated memory buffer

...


...

...

...

Improper null termination

...

Bibliography

...

 Chapter 2, "Strings" 
[Viega 2005]Section 5.2.14, "Miscalculated NULL

...

Termination"

...