Fortify indicates that this is an out of bounds read:
if (strncmp("test string", "less than 32 char", 32) == 0)
{
...
}
It says that the function reads data from outside the bounds of less than 32 char
.
Is there really a finding if strncmp
goes beyond 32 chars and the second string is less than 32 chars?
The strncmp() function in C++ compares a specified number of characters of two null terminating strings. The comparison is done lexicographically.
Presuming that the string in message is supposed to be null-terminated, the only reason to use strncmp() here rather than strcmp() would be to be to prevent it looking beyond the end of message , in the case where message is not null-terminated.
strncmp compares two character strings ( str1 and str2 ) using the standard EBCDIC collating sequence. The return value has the same relationship to 0 as str1 has to str2 . If two strings are equal up to the point at which one terminates (that is, contains a null character), the longer string is considered greater.
For performance reasons, implementations of the standard string functions will often process the data in naturally aligned register-width chunks. This can cause read access past the end of the source data objects, but the alignment guarantees that the code behaves exactly like a naive implementation with respect to memory exceptions. Each wide access is contained within a single page, and no pages are touched that would not also be touched by a byte-wise implementation.
I would claim that such implementations are covered by C's as-if rule, that is, they behave the same "as if" they were following the abstract functional specifications.
An example of such an optimized implementation would be OpenSolaris's strcmp()
for SPARC v8. This is code I wrote some fifteen years ago, along with other performance-optimized string functions.
Various memory checker tools will complain about such code, however, because its use can lead to access beyond the limits of the allocated data object, even though the out-of-bounds read access is harmless by design.
TL;DR - strncmp()
will keep comparing the string elements, until either the end of either string or 32 elements (characters), whichever is fewer.
A(ny) string is always null-terminated and upon encountering null-terminator, no further comparison is performed. Your code is safe.
Quoting C11
, chapter §7.24.4.4 (emphasis mine)
int strncmp(const char *s1, const char *s2, size_t n);
The
strncmp
function compares not more thann
characters (characters that follow a null character are not compared) from the array pointed to bys1
to the array pointed to bys2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With