[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: malloc and alignment

From: Miles Bader
Subject: Re: malloc and alignment
Date: 17 Jun 2003 11:25:32 +0900

"Stefan Monnier" <monnier+gnu/address@hidden> writes:
> > You could use `memalign'....
> How standard is it ?

Here's the glibc info page about it.  The traditional `portable' version
is exactly the sort of over-allocate-and-use-the-middle type thing you
mentioned.  I guess the biggest problem is how to _free_ such blocks --
as noted below, glibc can do so, but BSD can't (who knows how old that
info is, though)...


File: libc.info,  Node: Aligned Memory Blocks,  Next: Malloc Tunable 
Parameters,  Prev: Efficiency and Malloc,  Up: Unconstrained Allocation

Allocating Aligned Memory Blocks

   The address of a block returned by `malloc' or `realloc' in the GNU
system is always a multiple of eight (or sixteen on 64-bit systems).
If you need a block whose address is a multiple of a higher power of
two than that, use `memalign', `posix_memalign', or `valloc'.
`memalign' is declared in `malloc.h' and `posix_memalign' is declared
in `stdlib.h'.

   With the GNU library, you can use `free' to free the blocks that
`memalign', `posix_memalign', and `valloc' return.  That does not work
in BSD, however--BSD does not provide any way to free such blocks.

 - Function: void * memalign (size_t BOUNDARY, size_t SIZE)
     The `memalign' function allocates a block of SIZE bytes whose
     address is a multiple of BOUNDARY.  The BOUNDARY must be a power
     of two!  The function `memalign' works by allocating a somewhat
     larger block, and then returning an address within the block that
     is on the specified boundary.

 - Function: int posix_memalign (void **MEMPTR, size_t ALIGNMENT,
          size_t SIZE)
     The `posix_memalign' function is similar to the `memalign'
     function in that it returns a buffer of SIZE bytes aligned to a
     multiple of ALIGNMENT.  But it adds one requirement to the
     parameter ALIGNMENT: the value must be a power of two multiple of
     `sizeof (void *)'.

     If the function succeeds in allocation memory a pointer to the
     allocated memory is returned in `*MEMPTR' and the return value is
     zero.  Otherwise the function returns an error value indicating
     the problem.

     This function was introduced in POSIX 1003.1d.

 - Function: void * valloc (size_t SIZE)
     Using `valloc' is like using `memalign' and passing the page size
     as the value of the second argument.  It is implemented like this:

          void *
          valloc (size_t size)
            return memalign (getpagesize (), size);

     *Note Query Memory Parameters:: for more information about the
     memory subsystem.

The secret to creativity is knowing how to hide your sources.
  --Albert Einstein

reply via email to

[Prev in Thread] Current Thread [Next in Thread]