Archived

This topic is now archived and is closed to further replies.

jalan_gaurav

what is memory alignment

Recommended Posts

quote:
Original post by jalan_gaurav
hi,
does anybody know what memory alignment is? What are alignment restrictions? and why cant some data types have certain memory addresses?

Thanks.


mem alignment is where data sits on an address that is typically divisible by the system word size (eg 32-bits). alignment restrictions is where the data has to be aligned in order to be accessed by the cpu. for eg, running the following code on
a solaris/sparc would crash the program w/ a bus error....

char buf[10];
long *p = (long*)&buf[1];
*p = 1;

[edited by - ugenn on March 4, 2003 2:02:17 PM]

Share this post


Link to post
Share on other sites
IIRC, memory alignment is typically only an issue for RISC processors. They need data of an appropriate size to fit into an aligned boundary (i.e 32 bit data on 32 bit boundary, 64 bit data on 64 bit boudnary etc).

I believe it stems back to the fact that a RISC chip does not have the instruction set to be able to manipulate incorrectly alligned data properly, and will typically raise a CPU exception if it tries to access said misaligned data.

Ciao

Share this post


Link to post
Share on other sites
I''ve had "alignment" issues with structures:

struct s
{
char c;
int i;
}

where the size of the struct is NOT 5...

this means that you have to use the #pragma pack 1 (or whatever) if you want to fread that struct from a file.


That is the only time I''ve ever had a PROBLEM with memory alignment

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
even though unaligned accesses are (for the most part) allowed on x86, aligned accesses are MUCH faster. But your c/c++ compiler will keep everything aligned anyway, so unless you do really odd things you shouldn''t have to worry much.

Share this post


Link to post
Share on other sites