Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 25 Nov 2012 22:53:48 +0100
From:      Jilles Tjoelker <jilles@stack.nl>
To:        freebsd-hackers@FreeBSD.org
Cc:        Ed Schouten <ed@FreeBSD.org>
Subject:   Incorrect use of posix_memalign() (was: Re: svn commit: r243405 - in stable/9: include lib/libc/stdlib)
Message-ID:  <20121125215348.GB65833@stack.nl>
In-Reply-To: <201211221519.qAMFJroe007462@svn.freebsd.org>
References:  <201211221519.qAMFJroe007462@svn.freebsd.org>

next in thread | previous in thread | raw e-mail | index | archive | help
On Thu, Nov 22, 2012 at 03:19:53PM +0000, Ed Schouten wrote:
> Author: ed
> Date: Thu Nov 22 15:19:53 2012
> New Revision: 243405
> URL: http://svnweb.freebsd.org/changeset/base/243405

> Log:
>   MFC r229848:

>     Add aligned_alloc(3).

>     The C11 folks reinvented the wheel by introducing an aligned version of
>     malloc(3) called aligned_alloc(3), instead of posix_memalign(3). Instead
>     of returning the allocation by reference, it returns the address, just
>     like malloc(3).

>   I'm MFCing this now, as it seems aligned_alloc(3) is needed to make the
>   new version of libc++ work, which was merged back to FreeBSD 9 in r243376.

The C11 committee knew about posix_memalign() and had several reasons
for creating a new function; see for example
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1397.htm .

In particular, posix_memalign() is a little annoying to use correctly,
often requiring a temporary variable of type void *. It is tempting to
do something like
  error = posix_memalign((void **)&some_ptr, aln, sz);
and some FreeBSD code does this, but it violates strict-aliasing. A
further mostly theoretical objection is that assumes that the
representation of some_ptr and void * are compatible which C does not
guarantee.

The problem can be fixed by adding the temporary pointer variable like
  void *tmp_ptr;
  error = posix_memalign(&tmp_ptr, aln, sz);
  some_ptr = tmp_ptr;
or by using aligned_alloc() instead of posix_memalign()
  some_ptr = aligned_alloc(aln, sz);
with error checking against some_ptr instead of error.

-- 
Jilles Tjoelker



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20121125215348.GB65833>