简体   繁体   中英

can a struct assignment overlap similar to memmove() or is struct assignment like memcpy()?

There are two different functions for making a copy of a data area in the Standard C library, memmove() used for overlapping memory areas and memcpy() for disjoint, non-overlapping memory areas.

What does the C standards say about struct assignment as in:

struct thing myThing = {0};
struct thing *pmyThing = &myThing;

myThing = *pmyThing;     // assign myThing to itself through a pointer dereference.

Does the struct assignment follow the rules for memmove() or for memcpy() or its own rules so far as overlapping memory areas are concerned?

Section 6.5.16.1 ("Simple assignment") of the C standard (reading from draft N1548) states:

In simple assignment ( = ), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.

If the value being stored in an object is read from another object that overlaps in any way the storage of the first object, then the overlap shall be exact and the two objects shall have qualified or unqualified versions of a compatible type; otherwise, the behavior is undefined.

The C standard doesn't specify how the compiler implements the simple assignment. But overlap between the source and destination are permitted if the overlap is exact and the types are compatible. Self-assignment (whether through a pointer or not) meets this requirement, and thus the behavior is well-defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM