...
strncpy()
instead ofstrcpy()
strncat()
instead ofstrcat()
fgets()
instead ofgets()
snprintf()
instead ofsprintf()
Wiki Markup |
---|
These function truncate strings that exceed the specified limits. Additionally, some functions such as {{strncpy()}} do not guarantee that the resulting string is null-terminated \[[STR33-C |
Truncation results in a loss of data, and in some cases, leads to software
|STR33-C. Guarantee that all strings are null-terminated]\]. Truncation results in a loss of data, and in some cases, leads to software vulnerabilities. |
Non-Compliant Code Example
...
Code Block |
---|
char *string_data; char a[16]; ... strncpy(a, string_data, sizeof(a)); |
Compliant Solution 1
Truncation resulting from a string copy operation should be treated as an error condition.
Code Block |
---|
#define A_SIZE 16 char *string_data; char a[A_SIZE]; ... if (string_data) { if (strlen(string_data) < A_SIZEsizeof(a)) { strcpy(a, string_data); } else { /* handle string too large condition */ } } else { /* handle null string condition */ } |
Compliant Solution 2
Example using strcpy()
Compliant Solution 3
...
Wiki Markup |
---|
The {{strcpy_s()}} function provides additional safeguards including accepting the size of the destination buffer as an additional argument \[[STR00-A|STR00-A. Use TR 24731 for remediation of existing string manipulation code]\]. |
Code Block |
---|
#define A_SIZE 16
char *string_data;
char a[A_SIZE];
...
if (string_data) {
if (strlen(string_data) < sizeof(a)) {
strcpy(a, sizeof(a), string_data);
}
else {
/* handle string too large condition */
}
}
else {
/* handle null string condition */
}
|
Exception
An exception to this rule applies if the intent of the programmer was to intentionally truncate the null-terminated byte string. To be compliant with this standard, this intent must be made clear statement in comments.
...