Unless you have special requirements, using malloc is a smart approach. The advantage is that valgrind and the like can catch usage errors, which are one of the main ways that type of vulnerabilities can arise that might bother you. Since the OpenSSL debacle showed us trying to do something fancy and botting, this is a serious risk.
If you have more demanding requirements, it really depends a lot on your use case. I'm going to assume that your keys are transient, or to avoid storing them on disk does not make much sense. Here are my recommended mitigations for specific risks:
Switching to disk: if your system requires protection against physical attacks, you should not have swap at all. An individual attempt to protect certain data with mlock is a bit of a joke. Just swap and install enough memory, and that is not a problem. mlock should be seen as a real-time scheduling function, not a security function.
Heart failure problems, moderate protection: memory allocation via mmap with protective pages on both sides: first mmap is 2 pages larger than you need, all with PROT_NONE , then use mprotect to do everything except the first and last page PROT_READ|PROT_WRITE . Free it with munmap as soon as you are done with it.
Heart failure problems, strong protection: a child process widget to perform all cryptography.
source share