tech-userlevel archive

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

RE: aligned_alloc c11 function

> > > (On all real platforms, MIN_ALIGNMENT == sizeof(void *)
> >
> > Only for strange values of "real".  Platforms where sizeof(void *) is
> > not a power of two predate C (and are part of the reason why C has
> > that latitude built into it).
> >
> > Perhaps all, what was the phrase, "industrially relevant"
> > platforms....
> >
> Looking at the cpu architectures that NetBSD supports[1] I would I draw
> the conclusion that on all of them sizeof(void*) is either 4 or 8. Or am I
> wrong? So I think that using Terry's suggestion is fine.
> If anyone is against this please speak up.

Hi Niclas,

One of the things I really like about the NetBSD lists is that the people
are extremely serious about portability. I hadn't considered that
sizeof(void*) might not be power of 2; but Mouse was correct to point it
out. (And it was amusing to work out the solution using NetBSD notation, as
it were.)  I actually do know of machines in which sizeof(void*) is not a
power of two. They are moderately insane architectures, but sometimes one
has to deal with them.

There's no runtime efficiency cost for using <sys/bitops.h> and computing
the appropriate lg2 size ahead of time. We can argue about testing it,
there's also an argument for explicitly writing out the abstract property we
need. But the argument about testing is an argument *against* portability --
if you try to code for universality, including machines that don't exist
yet, you can never prove that you have it right. But the counter-argument is
that if you understand what the portability constraints & assumptions are,
you understand much more about what you're trying to compute, and therefore
are much less likely to make careless blunders. In my experience, the
counter-argument is persuasive.

If nothing else, NetBSD provides worked examples to the rest of the world
that portability doesn't have to be expensive at run time (though it
certainly requires a lot more thought while coding).

In any case: you can just have a trio of #defines:

#define LOWER_SIZEVOID  (1 << ilog2(sizeof(void *)))
#define MIN_ALIGN 	(sizeof(void *) == LOWER_SIZEVOID \

Then change the while() to "if (alignment < MIN_ALIGN) alignment =

(All the above intended to be adjusted to your preferred style / names /
line wrapping / etc. Obviously anything in a macro can be written out.)

But you're writing the code, so ultimately you get to decide!

Best regards,

Home | Main Index | Thread Index | Old Index