...
In the second noncompliant code example, memset()
is used to clear the destination buffer; unfortunately, the third argument incorrectly specifies the size of the destination array [Schwarz 2005].:
Code Block | ||||
---|---|---|---|---|
| ||||
char ntbs[NTBS_SIZE]; memset(ntbs, 0, sizeof(ntbs)-1); strncpy(ntbs, source, sizeof(ntbs)-1); |
...
In this compliant solution, the lessen_memory_usage()
function ensures that the resulting string is always properly null-terminated.:
Code Block | ||||
---|---|---|---|---|
| ||||
char *cur_msg = NULL; size_t cur_msg_size = 1024; /* ... */ void lessen_memory_usage(void) { char *temp; size_t temp_size; /* ... */ if (cur_msg != NULL) { temp_size = cur_msg_size/2 + 1; temp = realloc(cur_msg, temp_size); if (temp == NULL) { /* Handle error condition */ } cur_msg = temp; cur_msg_size = temp_size; /* Ensure string is null-terminated */ cur_msg[cur_msg_size - 1] = '\0'; } } /* ... */ |
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
| Can detect some violations of this rule. | ||||||
Coverity | 6.5 | STRING_NULL | Fully Implemented. | ||||||
| NNTS |
| |||||||
| 600 S | Fully implemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
[Schwarz 2005] | |
[Seacord 2013] | Chapter 2, "Strings" |
[Viega 2005] | Section 5.2.14, "Miscalculated NULL Termination" |
...
...