prevention of memory alignment issues?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

prevention of memory alignment issues?

Markus Lude-3
Hello,
I would like to know how you take care of memory alignment in C. First
idea is to reorder struct entries if possible. But why should oneself
need to do this. Isn't this the work for a compiler? Is there some
compiler switch or parameter so that the compiler could do the
alignment? Or are there one to prevent the compiler from doing this? As
a kind of last resort one could pad structs to align the entries by
hand, but is this really the solution?

Any hint appreciated.

Regards,
Markus

Reply | Threaded
Open this post in threaded view
|

Re: prevention of memory alignment issues?

Mark Kettenis
> Date: Sat, 17 Nov 2007 01:01:47 +0100
> From: Markus Lude <[hidden email]>
>
> Hello,
> I would like to know how you take care of memory alignment in C. First
> idea is to reorder struct entries if possible. But why should oneself
> need to do this. Isn't this the work for a compiler? Is there some
> compiler switch or parameter so that the compiler could do the
> alignment? Or are there one to prevent the compiler from doing this? As
> a kind of last resort one could pad structs to align the entries by
> hand, but is this really the solution?

The compiler takes care of the alignment if you use the appropriate
types.  Only when you are using casts you'll have to worry about
alignment.

Reply | Threaded
Open this post in threaded view
|

Re: prevention of memory alignment issues?

William Ahern-2
In reply to this post by Markus Lude-3
On Sat, Nov 17, 2007 at 01:01:47AM +0100, Markus Lude wrote:

> Hello,
> I would like to know how you take care of memory alignment in C. First
> idea is to reorder struct entries if possible. But why should oneself
> need to do this. Isn't this the work for a compiler? Is there some
> compiler switch or parameter so that the compiler could do the
> alignment? Or are there one to prevent the compiler from doing this? As
> a kind of last resort one could pad structs to align the entries by
> hand, but is this really the solution?
>
> Any hint appreciated.
>

The compiler _does_ take care of this. You're likely abusing the type
system. You very rarely ever need to cast object types in C. The common
exception is dealing with const qualifiers.

If you're treating your objects like just a bunch of bytes, then you're not
using C the way it was meant to be used. Some architectures, like x86, are
more forgiving when you abuse the system; SPARC, less so, as you seem to
have discovered. This is one of the reasons why SPARC is a better
environment for programming in C.