Function malloc

Source
pub fn malloc(size: usize) -> *mut c_void
Expand description

Secure memory allocation

This function allocates memory with extra protection, including:

  • Protection against buffer overflows
  • Protection against access after the memory is freed
  • Automatic zeroing when freed
  • Guarded pages to detect over/underflows

§Security Considerations

  • The allocated memory is automatically zeroed when freed
  • The memory is protected from being swapped to disk
  • This should be used for storing sensitive data like keys

§Example

use libsodium_rs as sodium;
use sodium::utils;
use std::slice;

// Allocate 32 bytes of secure memory
let ptr = utils::malloc(32);
assert!(!ptr.is_null());

// Use the memory
unsafe {
    let buf = slice::from_raw_parts_mut(ptr as *mut u8, 32);
    // Fill with data...
    for i in 0..32 {
        buf[i] = i as u8;
    }
}

// Free the memory (automatically zeroes it)
unsafe {
    utils::free(ptr);
}

§Arguments

  • size - The number of bytes to allocate

§Returns

  • *mut libc::c_void - A pointer to the allocated memory, or null if allocation failed