r6:Function:abstraction aligned malloc

From liblfds.org
Jump to: navigation, search

Source Files



void *abstraction_aligned_malloc( size_t size, size_t align_in_bytes );


size_t size

Number of bytes to allocate.

size_t align_in_bytes

Allocation alignment.

Return Value

Pointer to the allocated memory.


Typically platforms impose alignment restrictions on variables used in atomic instructions. ANSI C does not provide a malloc capable of honouring alignment requests. Major operating systems (Windows, Linux, Solaris, etc) do.

On such platforms implementation of this abstraction function is trivial since it is just a call to the operating system provided function.

On embedded platforms, there will be no operating system to provide such a function.

In this environment, the usual solution is to use normal malloc() to obtain the requested amount of memory plus a little more, such that we can return to the user a pointer to memory which begins at an aligned address. We also need to store a flag, just above the pointer we return to the user, which indicates, when we call abstraction_aligned_free, how much we have to subtract from the pointer the user gave us to get back to the actual original pointer returned by malloc().


Under POSIX 6.00 and later, there is a function to provide aligned memory allocation called posix_memalign, which has the following prototype;

int posix_memalign( void **memptr, size_t alignment, size_t size );

As such, the implementation of abstraction_aligned_malloc for a system providing POSIX 6.00 or greater looks like this;

#if (_XOPEN_SOURCE >= 600)

  /* TRD : any OS on any CPU with any compiler with POSIX 6.00 or better

           _XOPEN_SOURCE  is actually set by the user, not by the compiler
                          it is the way the user signals to the compiler what
                          level of POSIX should be available
                          (it assumes of course the compiler has support for the given level of POSIX requested)

  void *abstraction_aligned_malloc( size_t size, size_t align_in_bytes )


    rv = posix_memalign( &memory, align_in_bytes, size );

    // TRD : posix_memalign returns 0 on success, docs do not say *memory == NULL on fail
    if( rv != 0 )
      memory = NULL;

    return( memory );


See Also