#alloc #allocator #align #alignment #aligned


Provides cross-platform primitives for aligned memory allocation

4 releases

0.1.3 Jan 28, 2017
0.1.2 Jan 24, 2016
0.1.1 Oct 14, 2015
0.1.0 Oct 14, 2015

#79 in Memory management

Download history 663/week @ 2019-11-08 650/week @ 2019-11-15 792/week @ 2019-11-22 533/week @ 2019-11-29 680/week @ 2019-12-06 634/week @ 2019-12-13 374/week @ 2019-12-20 487/week @ 2019-12-27 596/week @ 2020-01-03 689/week @ 2020-01-10 643/week @ 2020-01-17 904/week @ 2020-01-24 882/week @ 2020-01-31 524/week @ 2020-02-07 519/week @ 2020-02-14

3,228 downloads per month
Used in 15 crates (6 directly)


127 lines

Aligned Allocations for Rust

Linux / OS X Windows
Build Status Build status

This crate provides cross-platform primitives for requesting specifically aligned allocations. It is not meant to be used as a general allocator API like alloc::heap, but can be used for infrequent large allocations that have a specific alignment requirement.

For example, certain arena allocators can find the arena in which an object was allocated by masking the address bits if the arena is aligned to its size.

On Unix, this crate makes use of the posix_memalign function. On Windows, it's a little more complicated: We use VirtualAlloc to reserve a chunk of address space large enough for the allocation plus alignment (no memory is actually allocated), then calculate an aligned address inside this reserved space, undo the reservation with VirtualFree (the extra bit of reserved memory for the alignment won't get wasted), and VirtualAlloc again, this time passing the aligned pointer and actually allocating the memory instead of just reserving address space.


As usual, in your Cargo.toml:

aligned_alloc = "0.1"

And in your lib.rs or bin.rs:

extern crate aligned_alloc;


The API is simple, there are just two methods:

fn aligned_alloc(size: usize, align: usize) -> *mut ()

Allocates size Bytes aligned to align Bytes. Returns a null pointer on allocation failure.

The returned pointer must be deallocated by using aligned_free.

Note: This function is meant to be used for infrequent large allocations (as malloc already guarantees suitable alignment for all native datatypes) and might be quite slow when used heavily.

  • size: The size of the allocation in bytes.
  • align: The alignment of the allocation (at least the size of usize on the current platform). Must also be a power of two.

unsafe fn aligned_free(ptr: *mut ())

Deallocates aligned memory that was allocated with aligned_alloc. Unsafe because calling this with a pointer that was not allocated with aligned_alloc (or already released) causes undefined behavior.