Null-terminated byte strings are, by definition, null-terminated. String operations cannot determine the length or end of strings that are not properly null-terminated, which can consequently result in buffer overflows and other undefined behavior.
Non-Compliant Code Example
The standard function functions strncpy()
and strncat()
do not guarantee that the resulting string is null terminated. If there is no null character in the first n
characters of the source array pointed , the result is may not be null-terminated, as in the following this example:
Code Block |
---|
char a[16]; strncpy(a, "0123456789abcdef", sizeof(a)); |
...
The correct solution depends on the programmers programmer's intent. If your the intent was to truncate a string but ensure that the
result was a null-terminated string the following , this solution can be used.:
Code Block |
---|
char a[16]; strncpy(a, "0123456789abcdef", sizeof(a)-1); a[sizeof(a)] = '\0'; |
...
The strncpy_s()
function copies not more than a maximum number n
of successive characters (characters that follow a null character are not copied) from the source array to a destination array. If no null character was copied from the source array, then the nth n
th position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated.
...
An exception to this rule applies if the intent of the programmer was is to convert a null-terminated byte string to a character array. To be compliant with this standard, this intent must be made clear statement clearly stated in comments.
Priority: P12 Level: L1
Failure to properly null terminate null-termianted terminated byte strings can result in buffer overflows and the execution of arbitrary code with the permissions of the vulnerable process by an attacker.
...