'data align'에 해당되는 글 1건

[[ blog 이사 과정에서 정확한 posting날짜가 분실됨. 년도와 분기 정도는 맞지 않을까? ]]

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

For example,

Int8* pt;
malloc(pData, 6);
pt = pData;
*pt = length;
*pt = width;
*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.

블로그 이미지


댓글을 달아 주세요