🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #114

Re: Aligning an arbitrary pointer?

#114
From: T. William Wells
Date: Fri, 24 Jul 1992 19:00
43 lines
2402 bytes
In article <14les7INN4m@early-bird.think.com> barmar@think.com (Barry Margolin) writes:
: Declare the structure as a union, where one case is an array of page table
: entries, and the other is the preceding stuff.  Then find the array element
: whose address is greater than the address of the end of the preceding
: stuff.  Use the address of that array element as the address of the page
: table.

Yes, that works. However, if the object is malloced, you don't
even need the union.

There's an awful lot of gobbledygook about this in the standard
but when all is said and done, the standard has eliminated the
notion that all objects are contained in a single address space.
However, each object still behaves as if it were a single address
space in the style to which we had become accustomed, with
increasing and contiguous addresses (in char*s) and the object's
alignment is determined by how it came into being. Malloced
objects are aligned with the strongest restriction possible in the
implementation.

Once you have an object, so long as you keep your pointers within
it (or at the end, provided you don't dereference the pointer)
and never generate an pointer with an alignment that is
incompatible with the alignment associated with its type, you can
do all the old pointer manipulation tricks we've all come to know
and love.

Suppose that you have a malloced area and a char pointer within
it. You suppose that the pointer points to the start of or to a
byte within some array element and you want to find the start of
the array element. This works:

	(array *)((char *)area +
		  (pointer - (char *)area)
		    / sizeof(array[0])
		    * sizeof(array[0]))

Watch out for ptrdiff_t oddities, though. (If those are a problem,
one is reduced to a certain amount of searching.)

---
Bill                            { uunet | decwrl | telesci }!twwells!bill
bill@twwells.com
Technical Details
Message-ID: <Brwq4F.Iqp@twwells.com>
Path: arc1-ca.pugleaf.net!sparky!uunet!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!pacbell.com!decwrl!twwells!bill
References: <14f6u9INNon7@early-bird.think.com> <PDS.92Jul21153918@lemming.webo.dg.com> <14les7INN4m@early-bird.think.com>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c
Path: arc1-ca.pugleaf.net!sparky!uunet!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!pacbell.com!decwrl!twwells!bill
From: bill@twwells.com (T. William Wells)
Subject: Re: Aligning an arbitrary pointer?
Organization: None, Mt. Laurel, NJ
References: <14f6u9INNon7@early-bird.think.com> <PDS.92Jul21153918@lemming.webo.dg.com> <14les7INN4m@early-bird.think.com>
Message-ID: <Brwq4F.Iqp@twwells.com>
Date: Fri, 24 Jul 1992 19:00:12 GMT
Lines: 43