[C/C++] Case study! Bad example about ignoring data-align..

We should not access memory address directly to read the value.
For example,

Int8* pt;
malloc(pData, 6);
pt = pData;
*pt = length;
pt++;
*pt = width;
pt++
*pt = (int)size; // ---(*)

This may create unexpected result due to data align. See (*). At (*), address of ‘pt’ is not 4-byte-aligned. But, it tries to write 4-byte-data (integer value). In this case, result may be compiler or target architecture dependent – usually, ‘size’ will be written at 4-byte-aligned-address.
Programmer who wrote above code may intent to make following memory state.

pData : [length(1 byte)][width(1 byte)][size(4 bytes]

But, usually, this may create following or undefined result.

pData : [length(1 byte)][width(1 byte)][padding(2 bytes)][size(4 bytes)]

So, we should not use like above(accessing memory directly). We can use ‘struct’ instead.
But, use ‘memcpy’ if above way is really needed.

(*) ==> memcpy(pt, &size, sizeof(size));

We should always keep it mind that data is aligned. So, directly accessing memory address to read or write data always has risk of compatibility with align.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s