...
| 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.
...