Secure Malloc project is a C library for secure memory allocations.
Most modern systems have some notion of swap, where the contents of memory can be written to disk, freeing up the memory for other purposes. This allows the system a lot of flexibility in managing its memory. Infrequently used data is a prime candidate for swapping to disk, thus freeing up the real memory for more useful purposes.
This can be a problem when using cryptography as there is a danger of keys or other sensitive data ending up in swap where (eventually) it may fall into the wrong hands. Secmalloc provides a secure version of the common 'malloc' interface for managing memory. All memory allocated by secmalloc is locked, so that it cannot be swapped out.
To use the library, create a structure of type struct secmalloc_config, fill it in, and pass it to secmalloc_init(). After that, you can call:
void *secmalloc(size_t size); /* use like malloc() */
void *seccalloc(size_t nmemb,size_t size); /* use like calloc() */
void secfree(void *ptr); /* use like free() */
void *secrealloc(void *ptr, size_t size); /* use like realloc() */
Do not pass a malloc()-ed pointer to secfree(), and similarly do not pass a secmalloc()-ed pointer to free().
More detailed documentation for the different fields of struct secmalloc_config are in the secmalloc.h header file, and there are several working code examples in the tests/ directory.
Locking by non-root users
On some platforms, only the root user can lock memory, but programmers obviously don't always want their programs to run as root. Secmalloc is designed to be able to handle this via the "initial_pools" option to secmalloc_init(). Secmalloc will allocate that number of locked memory pools immediately instead of allocating them as memory is requested. After secmalloc_init() returns, give up the setuid privileges. For example: