...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <string.h>
enum { STR_SIZE = 32 };
size_t func(const char *source) {
char c_str[STR_SIZE];
size_t ret = 0;
if (source) {
strncpy(c_str, source, sizeof(c_str) - 1);
c_str[sizeof(c_str) - 1] = '\0';
ret = strlen(c_str);
} else {
/* Handle null pointer */
}
return ret;
} |
Compliant Solution (
...
The C Standard, Annex K strncpy_s() function can also be used to copy with truncation. The strncpy_s() function copies up to n characters from the source array to a destination array. If no null character was copied from the source array, then the nth position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
enum { STR_SIZE = 32 };
size_t func(const char *source) {
char c_str[STR_SIZE];
size_t ret = 0;
if (source) {
errno_t err = strncpy_s(
c_str, sizeof(c_str), source, strnlen(source, sizeof(c_str))
);
if (err != 0) {
/* Handle error */
} else {
ret = strnlen(c_str, sizeof(c_str));
}
} else {
/* Handle null pointer */
}
return ret;
}
|
Compliant Solution (Copy without Truncation)
If the programmer's intent is to copy without truncation, this compliant solution copies the data and guarantees that the resulting array is null-terminated. If the string cannot be copied, it is handled as an error condition.
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Astrée |
| stdlib-string-termination | Partially checked + soundly supported Supported Astrée supports the implementation of library stubs to fully verify this guideline. | ||||||
| Axivion Bauhaus Suite |
| CertC-STR32 | Partially implemented: can detect some violation of the rule | ||||||
| CodeSonar |
| MISC.MEM.NTERM.CSTRING | Unterminated C String | ||||||
| Compass/ROSE | Can detect some violations of this rule | ||||||||
| Coverity |
| STRING_NULL | Fully implemented | ||||||
| Cppcheck Premium |
| premium-cert-str32-c | |||||||
| Helix QAC |
| DF2835, DF2836, DF2839 | |||||||
| Klocwork |
| NNTS.MIGHT | |||||||
| LDRA tool suite |
| 404 S, 600 S | Partially implemented | ||||||
| Parasoft C/C++test |
| CERT_C-STR32-a | Avoid overflow due to reading a not zero terminated string | ||||||
| Polyspace Bug Finder |
| Checks for:
Rule partially covered. | |||||||
| PVS-Studio |
| V692 | |||||||
| RuleChecker |
| stdlib-string-termination | Partially checked | ||||||
| Security Reviewer - Static Reviewer |
| shiftTooManyBits | Fully implemented | ||||||
| TrustInSoft Analyzer |
| match format and arguments | Partially verified. |
...