...
Code Block | ||
---|---|---|
| ||
char *secret; /* initialize secret */ char *new_secret; size_t size = strlen(secret); if (size == SIZE_MAX) { /* Handle error */ } /* use calloc() to zero-out allocated space */ new_secret = (char *)calloc(size+1, sizeof(char)); if (!new_secret) { /* Handle error */ } strcpy(new_secret, secret); /* Process new_secret... */ /* sanitize memory */ memset((volatile char *)_s(new_secret, '\0', size); free(new_secret); new_secret = NULL; |
The calloc()
function ensures that the newly allocated memory has also been cleared. Because sizeof(char)
is guaranteed to be 1, this solution does not need to check for a numeric overflow as a result of using calloc()
(see MEM07-C. Ensure that the arguments to calloc(), when multiplied, can be represented as a size_t).
NOTE: It is possible that the call to memset()
in this example will be optimized out, although casting new secret
as a volatile character should prevent this (see See MSC06-C. Be aware of compiler optimization when dealing with sensitive data for a definition and discussion of using the memset_s()
. Be very careful to ensure that any sensitive data is actually cleared from memory. function.
Noncompliant Code Example: realloc()
...
Wiki Markup |
---|
\[[Fortify 06|AA. C References#Fortify 06]\] \[[Graff 03|AA. C References#Graf 03]\] \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3, "Memory management functions" \[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "XZK Sensitive Information Uncleared Before Use" |
Wiki Markup |
---|
\[[MITRE 07|AA. C References#MITRE 07]\] [CWE ID 226|http://cwe.mitre.org/data/definitions/226.html], "Sensitive Information Uncleared Before Release," [CWE ID 244|http://cwe.mitre.org/data/definitions/244.html], and "Failure to Clear Heap Memory Before Release"
\[[NIST 06b|AA. C References#NIST 06b]\] |
...