...
However, note that both calling functions and accessing volatile-qualified objects can still be optimized out (while maintaining strict conformance to the standard), so this compliant solution still might not work in some cases. The memset_s() function introduced in C11 is the preferred solution (see the following solution for more information). If memset_s() function is not yet available on your implementation, this compliant solution is the best alternative, and can be discarded once supported by your implementation.
Compliant Solution (C11, Annex K)
As of C11, tAnnex K of the C Standard includes a memset_s function. Subclause K.3.7.4.1, paragraph 4 [ISO/IEC 9899:2011], states:
Unlike
memset, any call to thememset_sfunction shall be evaluated strictly according to the rules of the abstract machine as described in (5.1.2.3). That is, any call to thememset_sfunction shall assume that the memory indicated bysandnmay be accessible in the future and thus must contain the values indicated byc.
Note that Annex K is conditionally normative, so it may not be available on all platforms.
| Code Block | ||||
|---|---|---|---|---|
| ||||
void getPassword(void) {
char pwd[64];
if (retrievePassword(pwd, sizeof(pwd))) {
/* Checking of password, secure operations, etc. */
}
memset_s(pwd, 0, sizeof(pwd));
}
|
Noncompliant Code Example
...