Re: [linux-usb] Re: How to get aligned memory?

Richard B. Johnson (root@chaos.analogic.com)
Fri, 31 Jul 1998 09:18:11 -0400 (EDT)


On Fri, 31 Jul 1998, Rogier Wolff wrote:

> Richard B. Johnson wrote:
> > On 30 Jul 1998, Michael Poole wrote:
> >
> > > "Richard B. Johnson" <root@chaos.analogic.com> writes:
> > >
> > > > This can be done in one line, with one pointer, but I will do it
> > > > step-by-step....
> > > >
[SNIPPED]
> > >
> > > Actually, that's guaranteed to waste at least one byte. The allocation of
> > > foo only needs to grab 15 extra bytes, and the "foo += 0x10" should
> > > be "foo += 0x0f" -- if foo is magically aligned to a 16-byte offset before
> > > you get it, then there's very little point in shifting it up to the next
> > > 16-byte block.
> > >
> >
> > Picky, picky. I wouldn't really do it either way because the compiler
> > will not allow binary operations upon a pointer. The idea was to
> > demonstrate the mechanism, i.e., allocate something big enough and
> > do the alignment yourself.
>
> P.S. Malloc usually returns 16-byte aligned stuff. (At least when I
> wrote the darn thing :-)
>
> Roger.
>
Well, try it for yourself. It appears to end in '8' on my machine.

#include <stdio.h>
#include <malloc.h>

#define ALIGN 0x0100 /* Any 'power-of-2' alignment */

typedef struct { /* structure to be aligned */
short one;
short two;
short three;
short four;
} BARF;

int main()
{
union { /* This just allows the compiler to compile */
unsigned long l; /* It should not generate (much) extra code */
BARF *b;
} m;

char *save;
if((save = (char *) malloc(sizeof(BARF) + ALIGN)) == NULL)
exit(1);
m.b = (BARF *) save;
printf("Pointer : %p\n", (void *) m.b);
printf(" Raw : 0x%08lX\n", m.l);
m.l = (m.l + (ALIGN -1)) & ~(ALIGN -1); /* Do alignment thing */
printf("Aligned : 0x%08lX\n", m.l);
m.b->one = 0x0001; /* Access the aligned structure */
m.b->two = 0x0002;
m.b->three = 0x0003;
m.b->four = 0x0004;
printf("one = %04x, two = %04x, three = %04x, four = %04x\n",
m.b->one = 0x0001,
m.b->two = 0x0002,
m.b->three = 0x0003,
m.b->four = 0x0004 );

free(save);
return 0;
}

Cheers,
Dick Johnson
***** FILE SYSTEM MODIFIED *****
Penguin : Linux version 2.1.111 on an i586 machine (66.15 BogoMips).
Warning : It's hard to remain at the trailing edge of technology.

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.rutgers.edu
Please read the FAQ at http://www.altern.org/andrebalsa/doc/lkml-faq.html