CKTIS / C
memset_explicit — explicit memory overwriting
The C23 function memset_explicit fills a specified memory region with a chosen byte. It is intended to erase sensitive data without the optimizer removing the write as an unnecessary operation.
Version: C23; repository compiler flag, production runtime not attested
Syntax
#include <string.h>
void *memset_explicit(void *s, int c, size_t n);memset_explicit, declared in <string.h>, writes c, converted to unsigned char, into the first n bytes of the object pointed to by s. It returns s, not a success code. n is a byte count, not a text length.
Unlike memset, this function is intended for overwriting sensitive data: the footnote in N3096 explains the intention that optimization never remove the write, even when the program will not read the buffer again. This does not imply erasure of other copies, such as data previously stored in another buffer or on disk.
Supply a valid pointer to writable memory and an appropriate size: the function receives no buffer capacity and performs no bounds checking. Overwrite data before the object's lifetime ends. In the example, sizeof secret covers the whole array; for a pointer, sizeof does not give the pointed-to buffer's size.
The function belongs to C23. A repository compiler flag alone does not establish that the target C library provides its declaration and implementation; production runtime support has not been attested.
Examples
#include <stddef.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
unsigned char secret[] = {1, 2, 3, 4};
void *result = memset_explicit(secret, 0, sizeof secret);
int cleared = 1;
for (size_t i = 0; i < sizeof secret; ++i) {
if (secret[i] != 0) cleared = 0;
}
printf("cleared=%d same_pointer=%d\n", cleared, result == (void *)secret);
return 0;
}
Result
cleared=1 same_pointer=1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.