Implement aligned_alloc().

Implement aligned_alloc(), which was added in the C11 standard.  The
function is weakly specified to the point that a minimally compliant
implementation would be painful to use (size must be an integral
multiple of alignment!), which in practice makes posix_memalign() a
safer choice.
This commit is contained in:
Jason Evans
2012-03-13 12:55:21 -07:00
parent 4c2faa8a7c
commit 0a0bbf63e5
8 changed files with 218 additions and 14 deletions

View File

@@ -30,6 +30,7 @@
<refname>malloc</refname>
<refname>calloc</refname>
<refname>posix_memalign</refname>
<refname>aligned_alloc</refname>
<refname>realloc</refname>
<refname>free</refname>
<refname>malloc_usable_size</refname>
@@ -73,6 +74,11 @@
<paramdef>size_t <parameter>alignment</parameter></paramdef>
<paramdef>size_t <parameter>size</parameter></paramdef>
</funcprototype>
<funcprototype>
<funcdef>void *<function>aligned_alloc</function></funcdef>
<paramdef>size_t <parameter>alignment</parameter></paramdef>
<paramdef>size_t <parameter>size</parameter></paramdef>
</funcprototype>
<funcprototype>
<funcdef>void *<function>realloc</function></funcdef>
<paramdef>void *<parameter>ptr</parameter></paramdef>
@@ -190,6 +196,14 @@
<parameter>alignment</parameter> must be a power of 2 at least as large
as <code language="C">sizeof(<type>void *</type>)</code>.</para>
<para>The <function>aligned_alloc<parameter/></function> function
allocates <parameter>size</parameter> bytes of memory such that the
allocation's base address is an even multiple of
<parameter>alignment</parameter>. The requested
<parameter>alignment</parameter> must be a power of 2. Behavior is
undefined if <parameter>size</parameter> is not an integral multiple of
<parameter>alignment</parameter>.</para>
<para>The <function>realloc<parameter/></function> function changes the
size of the previously allocated memory referenced by
<parameter>ptr</parameter> to <parameter>size</parameter> bytes. The
@@ -1789,6 +1803,27 @@ malloc_conf = "xmalloc:true";]]></programlisting>
</variablelist>
</para>
<para>The <function>aligned_alloc<parameter/></function> function returns
a pointer to the allocated memory if successful; otherwise a
<constant>NULL</constant> pointer is returned and
<varname>errno</varname> is set. The
<function>aligned_alloc<parameter/></function> function will fail if:
<variablelist>
<varlistentry>
<term><errorname>EINVAL</errorname></term>
<listitem><para>The <parameter>alignment</parameter> parameter is
not a power of 2.
</para></listitem>
</varlistentry>
<varlistentry>
<term><errorname>ENOMEM</errorname></term>
<listitem><para>Memory allocation error.</para></listitem>
</varlistentry>
</variablelist>
</para>
<para>The <function>realloc<parameter/></function> function returns a
pointer, possibly identical to <parameter>ptr</parameter>, to the
allocated memory if successful; otherwise a <constant>NULL</constant>