c++ - C aliasing rules and memcpy -


While answering another question, I thought of the following example:

  Void * p; Unsigned x = 17; Emphasis (size) (zero *)> = sizeof (unsigned)); * (Unsigned *) & amp; P = 17; // (1) mempi (and p, and x, size (x)); // (2)  

Line 1 aliasing breaks the rule Line 2, though, is ok wrt. Eliasing rule is the question: why? Does the compiler have special inherent knowledge about functions such as mempi, or are there some other rules that make Memky OK? Is there a way to implement the memcopy-like function in standard C without breaking the rules of the Eliza?

"post-text" itemprop = "text">

strong> C standard is quite clear on this. The effective type of object named p is zero * , because it has a declared type, see 6.5 / 6 . In the C99, the algorithm writes and , and writes zero * via unsigned lvalue (1) > 6.5 / 7> has undefined behavior.

On the contrary, memcpy is of (2) , because unsigned char * is any object ( 6.5 / 7 / ). Standard for each of the functions in this code, each character will be explained, such as memcpy on 7.21.2 / 1 like

type unsigned char (And therefore every possible object representation is valid and has a different value).

Memkky function copies n characters in the object indicated by s2 from the object, if the copy is copied between the copied objects, then the behavior has been removed.

However, if it is present in the after p , the reason for this may be due to undefined behavior is little practice. If this is not an experiment, then this code is fine in C. According to the C ++ standard , which in my opinion is not clear on this issue, I think the following holds that this interpretation is possible only as possible Do not take in - The ambiguous / incomplete specification leaves plenty of room for betting.

line (1) is problematic because & amp; P alignment can not be correct for the type of unsigned type it changes the type of object stored in p to unsigned int . As long as you do not access that object through p , aliasing rules are not broken, but alignment requirements may still be

line (2) Although there is no alignment problem, and thus valid, as long as you have p later zero * , due to which the reason of undefined behavior It may be that how the zero * type describes the bitpattern stored by me In that type of object is changed as follows.

There is a long time that discusses the implications of writing through such potter as a result of such artists and what is the difference between the placements (people in that list Do not agree with what it is).


Comments