← Back to section · Tutorials & Labs

Memory Management and Key Destruction in the liboqs C API

liboqs keeps key material in caller-managed buffers: how the length fields of the OQS_KEM object define every allocation, who allocates and who frees, and the correct OQS_MEM_cleanse procedure for destroying secret keys.

Published 22 November 2026 · 6 min read · PQ Frontier

Memory Management and Key Destruction in the liboqs C API
AI-generated site artwork
Video explainer · C/C++ cryptography: libraries and implementation

Start With liboqs’ Division of Responsibility

liboqs is the C core library of the Open Quantum Safe project, and its interface is deliberately thin: the library does the algorithm math, while memory ownership is divided crisply. Each algorithm is represented by a descriptor object — OQS_KEM_new("ML-KEM-768") returns an OQS_KEM * by name — which carries function pointers plus a set of length fields: length_public_key, length_secret_key, length_ciphertext and length_shared_secret. These fields are the foundation of all memory management here: every buffer size is read from them, and concrete numbers like 1184 or 1088 must never be written into code. The reason is practical — the same code retargeted at ML-KEM-1024 or ML-DSA has entirely different sizes; code that reads the fields needs no change, while hard-coded code silently overflows on some parameter set. A second point is the enablement list: if an algorithm was not compiled into the library, OQS_KEM_new returns NULL, so the creation result must always be null-checked — a different style from libraries that guarantee presence at link time.

Who Allocates, Who Frees

Key generation, encapsulation and decapsulation all share one signature pattern: the caller allocates the output buffers from the length fields and passes pointers in; the function only writes. Key generation, for example:

#include <oqs/oqs.h>

OQS_KEM *kem = OQS_KEM_new(OQS_KEM_alg_ml_kem_768);
if (kem == NULL) { /* algorithm not enabled */ }
uint8_t *pk = malloc(kem->length_public_key);
uint8_t *sk = malloc(kem->length_secret_key);
uint8_t *ct = malloc(kem->length_ciphertext);
uint8_t *ss = malloc(kem->length_shared_secret);
if (OQS_KEM_keypair(kem, pk, sk) != OQS_SUCCESS) { /* handle failure */ }
if (OQS_KEM_encaps(kem, ct, ss, pk) != OQS_SUCCESS) { /* handle failure */ }
if (OQS_KEM_decaps(kem, ss, ct, sk) != OQS_SUCCESS) { /* handle failure */ }

Three traps hide here. First, the return value is the OQS_STATUS enum and success is OQS_SUCCESS — the exact opposite of OpenSSL’s “positive means success” convention, and the easiest thing to get wrong when migrating from the other library. Second, the algorithm name can be given either as the string "ML-KEM-768" or as the header constant OQS_KEM_alg_ml_kem_768; the constant catches typos at compile time, so production code should prefer it. Third, every malloc result must be null-checked: key material is small, but writing through a failed allocation is memory corruption. The signature side is perfectly symmetric — the object becomes OQS_SIG, the length fields become length_public_key, length_secret_key and length_signature, and the destructor is OQS_SIG_free.

Destruction: Wipe First, Then Free

Ordinary data can simply be freed; key material cannot. free returns memory to the allocator while the bytes stay in place, ready to leak through reuse or a memory dump. The correct destruction order is wipe, then free. liboqs provides OQS_MEM_cleanse(void *ptr, size_t len) in its common utilities, which guarantees the wipe is not optimized away by the compiler as a dead store. The full teardown looks like this:

OQS_MEM_cleanse(sk, kem->length_secret_key);
OQS_MEM_cleanse(ss, kem->length_shared_secret);
free(sk);
free(ss);
free(pk);
free(ct);
OQS_KEM_free(kem);

Public keys and ciphertexts do not strictly need wiping — they are transmitted in the open anyway — but wiping them too is harmless, and team standards often simply require “every buffer obtained for liboqs gets cleansed before free” to avoid case-by-case judgment. Remember also stack-resident secrets: decapsulation intermediates and derived session keys held in stack arrays must be wiped before the function returns, because returning does not zero stack memory. Finally, OQS_MEM_cleanse only solves the compiler problem; core dumps and swap at the OS level are outside its reach and need system-level measures in production — this tutorial stays at the library interface layer.

Compare Secrets With Library Functions Too

When checking that two shared secrets match, the beginner’s reflex is memcmp(a, b, len) == 0. The problem is that memcmp returns at the first differing byte, so the comparison time varies with the position of the first difference, and an attacker who measures repeatedly can guess the secret byte by byte — a textbook timing side channel. liboqs provides OQS_MEM_secure_bcmp, which compares in constant time; note that its return convention is the mirror of memcmp: 0 when equal, -1 when not, so read the comment before using it. The deeper principle is that production protocols should never contain a “compare the shared secret directly” step at all: both sides should derive keys and complete a key-confirmation handshake. The legitimate uses of OQS_MEM_secure_bcmp are test code and protocol self-checks. Make “sizes from fields, wipe before free, compare with the secure function” standing rules and liboqs memory management will not cause you serious trouble.

Worth Knowing Alongside: Algorithm Lists and the Randomness Interface

Beyond memory, two interface families are closely tied to lifecycle management and worth learning together. The first is the algorithm inventory: OQS_KEM_alg_count() returns how many KEM algorithms this build enables, OQS_KEM_alg_identifier(i) fetches a name by index, and OQS_KEM_alg_is_enabled(name) tests whether a given algorithm is available — the signature side has a fully parallel OQS_SIG_ family. Printing this list at startup, or diffing it against an expected manifest, is a nearly free self-check: an algorithm that was never compiled in, or build switches that pruned too much, are far better discovered at initialization than as a NULL in the middle of business logic. The second is randomness: liboqs uses its own randomness source internally when generating keys, and application code needing cryptographic randomness can draw bytes with OQS_randombytes(buffer, length), whose backend defaults to the operating system’s source. What engineering must avoid is several randomness sources mixed together with separate seeding: feeding anything beyond test vectors from rand() or a fixed seed breaks the entire security argument. When test vectors need deterministic randomness, swap the backend through the library’s switchable randomness interface in the test target only, and keep the production build on the default backend — draw that boundary in the build system.

End with a size-related habit: wherever key material is placed into a struct, a protocol message or a file format, record its length explicitly alongside and validate it on use. liboqs only guarantees that it reads and writes the byte counts it is given; everything beyond the buffer — a length field sent by a network peer, the actual size of a file on disk — is outside its guarantees. A large share of historical vulnerabilities came precisely from trusting externally declared lengths: an operation whose declared length exceeds the real buffer is an out-of-bounds access inside liboqs’ functions. Carve “lengths come from the object’s fields; external lengths are always validated first” into the calling convention, and this article’s memory discipline closes its loop.

Summary

The liboqs memory model in one sentence: the library supplies sizes and algorithms; the caller owns allocation and destruction. Pair OQS_KEM_new with OQS_KEM_free, always read buffer sizes from the length fields, wipe secret keys and shared secrets with OQS_MEM_cleanse before freeing, and compare secrets with OQS_MEM_secure_bcmp. The next article shows how C++ RAII turns this manual discipline into rules the compiler enforces, so that forgetting to wipe or to free becomes impossible to write.

Tags: liboqsCMemory SafetyML-KEM