This function takes an amount (called size) and returns a pointer from which
exactly size contiguous bytes of memory can be accessed. The pointer may be
nullPtr and there may be an error when allocating memory,
through errno. Upon failure, errno will be set to eNOMEM
It is recommended that the caller use Foreign.C.Error to handle potential failure.
Moreover, sodiumInit must be called before using this
function.
Explanation
The allocated region is placed at the end of a page boundary,
immediately followed by a guard page (or an emulation,
if unsupported by the platform). As a result, accessing memory past the end of the
region will immediately terminate the application.
A canary is also placed right before the returned pointer. Modifications of this
canary are detected when trying to free the allocated region with sodiumFree
and cause the application to immediately terminate.
If supported by the platform, an additional guard page is placed before this canary
to make it less likely for sensitive data to be accessible when reading past the end
of an unrelated region.
The allocated region is filled with 0xdb bytes to help catch bugs due to
uninitialized data.
In addition, mlock(2) is called on the region to help avoid it being swapped to disk.
Note however that mlock(2) may not be supported, may fail or may be a no-op,
in which case sodiumMalloc will return the memory regardless, but it will not be
locked. If you specifically need to rely on memory locking, consider calling
sodiumMlock and checking its return value.
On operating systems supporting MAP_NOCORE or MADV_DONTDUMP, memory allocated this
way will also not be part of core dumps.
The returned address will not be aligned if the allocation size is not a multiple
of the required alignment.
For this reason, sodiumMalloc should not be used with packed or variable-length
structures unless the size given to sodiumMalloc is rounded up to ensure proper
alignment.
All the structures used by libsodium can safely be allocated using
sodiumMalloc.
Allocating 0 bytes is a valid operation. It returns a pointer that can be
successfully passed to sodiumFree.
⚠️ This is not a general-purpose allocation function, and requires 3 or 4 extra
pages of virtual memory. Since it is very expensive, do not use it to allocate
every-day memory.
See: sodium_malloc()