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.
'Language > C&C++' 카테고리의 다른 글
[C/C++] API to getting bufferred data... (0) | 2008.01.06 |
---|---|
[C/C++] Use instantiate-function(factory function) to hide concreate class... (0) | 2007.12.13 |
[C/C++] Case study! Bad example about endianness. (0) | 2007.06.29 |
[C/C++] Sample! inter-change between endians... (0) | 2007.06.28 |
[C/C++] Avoiding symbol conflict when release library... (0) | 2007.05.19 |