I am going through the following link to understand memory alignment: https://www.ibm.com/developerworks/library/pa-dalign/#N10159. However I am not able to understand the code snippet given below.
void Munge8( void *data, uint32_t size ) {
uint8_t *data8 = (uint8_t*) data;
uint8_t *data8End = data8 + size;
while( data8 != data8End ) {
*data8++ = -*data8;
}
}
Here the intent is to increment the pointer and that could have been done by "data8 = data8 + 1" but the code in question uses "*data8++ = -*data8". Both of them work fine i.e. increment the pointer but I am unable to understand the logic behind the later. Is it better than "data8 = data8+1"?
During compilation I get an error "alignment_test1.c:44: warning: operation on ‘data8’ may be undefined".
The second part of the question is regarding the code snippet below (from the same link mentioned earlier).
Listing 2. Munging data two bytes at a time
void Munge16( void *data, uint32_t size ) {
uint16_t *data16 = (uint16_t*) data;
uint16_t *data16End = data16 + (size >> 1); /* Divide size by 2. */
uint8_t *data8 = (uint8_t*) data16End;
uint8_t *data8End = data8 + (size & 0x00000001); /* Strip upper 31 bits. */
while( data16 != data16End ) {
*data16++ = -*data16;
}
while( data8 != data8End ) {
*data8++ = -*data8;
}
}
What could be the reason behind the second 'while' loop? Because data8 and data8End are always going to be same in this case.
The code from that article is a buggy mess. Do not read or study it. Stop reading the article immediately.
*data8++ = -*data8;
invokes undefined behavior, since it contains unsequenced access to data8
. See the most common C FAQ of all time: Why are these constructs (using ++) undefined behavior?
Depending on the original type of the data, the second part is very likely to contain various forms of strict aliasing behavior, another form of undefined behavior. You cannot convert pointer-to-something to pointer-to-uint16_t and then access the content as if it was a uint16_t
, unless that was the original type of the object (effective type). This leads us to another common C FAQ, What is the strict aliasing rule?
You can direct the author of that article to those links and tell them to go study basic C programming, before attempting to publish technical articles on the internet.
User contributions licensed under CC BY-SA 3.0