This is related to this question: is there is a way to memset a buffer after finished using it (for security for example) without it being optimized out?
Trying to cast the pointer to volatile pointer getting warning about sending volatile pointer to function that not expects volatile.
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 ofmemset_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 callingmemset_s()(if available), adding a memory barrier after a call tomemset(), or if none of those can be used, callingmemset()via a volatile function pointer. The use of a volatile function pointer involves defining and initializing a function pointervolatile_memsetlike this:Calls to
memset()through thevolatile_memsetpointer will not be optimized away.