The memset_explicit()
function from the C23 draft standard does what you want, but might not be implemented in current versions of the C standard library. The GNU Gnulib (GNU Portability Library) includes a version of memset_explicit()
that can be incorporated in a project's sources under the terms of the GNU Lesser General Public License. The initial import into a project assumes that the project uses Autoconf, so that could be a problem for projects that do not use Autoconf.
The Gnulib implementation of memset_explicit()
uses conditional compilation to implement the function in various ways, such as calling memset_s()
(if available), adding a memory barrier after a call to memset()
, or if none of those can be used, calling memset()
via a volatile function pointer. The use of a volatile function pointer involves defining and initializing a function pointer volatile_memset
like this:
void * (* const volatile volatile_memset) (void *, int, size_t) = memset;
Calls to memset()
through the volatile_memset
pointer will not be optimized away.