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
_______________________________________________
freebsd-hackers@freebsd.org mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-hackers
To unsubscribe, send any mail to "freebsd-hackers-unsubscr...@freebsd.org"

Reply via email to