1. Krister Walfridsson. Aliasing, pointer casts and gcc 3.3.
2. Mike Acton. Understanding Strict Aliasing.
The main idea is simple:
Pointer casts are evil (both explicit and implicit casts), and you should think twice before adding a pointer cast to the code...Scott Meyers says about it softer:
If you’re coming to C++ from C, Java, or C#, take note, because casting in those languages is more necessary and less dangerous than in C++. But C++ is not C. It’s not Java. It’s not C#. In this language, casting is a feature you want to approach with great respect.Key points:
1. One pointer is said to alias another pointer when both refer to the same location or object.
2. Pointers of different types cannot point to the same address.
3. Code below:
intCompiler may optimize as:
foo(float *f) {
int i = 23;
*f = 5.0;
/* A float* cannot point on the same address as int*. */
return i * 2;
}
int4. Many architectures requires that pointers are correctly aligned when
foo(float *f) {
*f = 5.0;
return 46;
}
accessing objects bigger than a byte. So the following code may not work:
char* data;The reason is that the behavior is undefined when you assign an unaligned value to a pointer that points to a type that need to be aligned. What happens in the example above is that compiler notices that tmp and header must be aligned, so it may use an inlined memcpy that uses instructions that assumes aligned data.
struct foo_header *tmp, header;
tmp = data + offset;
memcpy(&header, tmp, sizeof(header));
Here is fix:
char* data;
struct foo_header header;
memcpy(&header, data + offset, sizeof(header));
No comments:
Post a Comment