tech-userlevel archive

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

RE: aligned_alloc c11 function



> >>> but a purist might want to use compile-time log2 macros to compute
> >>> MIN_ALIGNMENT.)
> >> How does one do that?  [...]
> > Using ?: for a binary search comes to mind.
> 
> You have to put a hard maximum on the result for that to work, no?
> That is, you have to assume that the thing you want to take lg of
> (sizeof(void *), in ths case) is not greater than some maximum value, a
> maximum which cannot be raised without hacking on the source.

You can take lg2 of a UINT64 at compile time with a maximum of 64 compares
in a ?: chain. sizeof(void*) must be relatively small compared to
UINT64_MAX, otherwise that while() loop has other problems.

ilog2() in netbsd5's sys/bitops.h does exactly this if the parameter is a
constant.  So ilog2(sizeof(void*)) will be a compile-time (not
preprocessor-time) constant. There is work to be done to deal with the
low-order bits.

Here's a little test program:

-------
#include <stdint.h>	/* needed for bitops.h */
#include <stdio.h>
#include <sys/bitops.h>

/* allow overrides, but check interesting case by default */
#ifndef SIZEVOID
# define SIZEVOID       sizeof(void *)
#endif

/* write out the calculation for clarity */
#define LOWER_SIZEVOID  (1 << ilog2(SIZEVOID))
#define UPPER_SIZEVOID  (LOWER_SIZEVOID << 1)
#define MIN_ALIGN 	(SIZEVOID == LOWER_SIZEVOID ? LOWER_SIZEVOID :
UPPER_SIZEVOID)

/* proves that minalign is a compile-time constant: */
static const size_t minalign = MIN_ALIGN;

int main(int ac, char **av)
        {
        printf("SIZEVOID = %u minalign = %u\n", (unsigned) SIZEVOID,
(unsigned) minalign);
        }
------

A few tests:

$ cc -o logtest /tmp/logtest.c && logtest
SIZEVOID=4 minalign = 4

$ cc -DSIZEVOID=7 -o logtest /tmp/logtest.c && logtest
SIZEVOID=7 minalign = 8

Best regards,
--Terry

> -----Original Message-----
> From: tech-userlevel-owner%NetBSD.org@localhost [mailto:tech-userlevel-
> owner%NetBSD.org@localhost] On Behalf Of Mouse
> Sent: Saturday, October 31, 2015 11:11
> To: tech-userlevel%NetBSD.org@localhost
> Subject: Re: aligned_alloc c11 function
> 
> 
> /~\ The ASCII				  Mouse
> \ / Ribbon Campaign
>  X  Against HTML		mouse%rodents-montreal.org@localhost
> / \ Email!	     7D C8 61 52 5D E7 2D 39  4E F1 31 3E E8 B3 27 4B



Home | Main Index | Thread Index | Old Index