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?
The CRT function memcpy doesn't support overlapping memory. The CRT provides an alternative to memcpy that does support overlapping memory: memmove .
memmove() is similar to memcpy() as it also copies data from a source to destination. memcpy() leads to problems when source and destination addresses overlap as memcpy() simply copies data one by one from one location to another. For example consider below program.
memmove has nothing to do with clearing the old memory, and in fact in the only situations where you would want to use memmove , clearing the old memory would destroy the data you just copied! That's because memmove is only useful when you expect the source and destination ranges to overlap.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With