r6.0.0:lfds600_abstraction_aligned_malloc

From liblfds.org
Revision as of 14:07, 4 January 2015 by Admin (talk | contribs) (1 revision imported)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Source Files

/liblfds600/src/lfds600_abstraction/lfds600_abstraction_aligned_malloc.c
/liblfds600/inc/liblfds600.h

Prototype

void *lfds600_abstraction_aligned_malloc( size_t size, size_t align_in_bytes );

Parameters

size_t size

Number of bytes to allocate.

size_t align_in_bytes

Allocation alignment.

Return Value

Pointer to the allocated memory.

Notes

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 lfds600_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().

Examples

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 lfds600_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 *lfds600_abstraction_aligned_malloc( size_t size, size_t align_in_bytes )
  {
    int
      rv;

    void
      *memory;

    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 );
  }

#endif

See Also