Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

standards

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?

like image 774
Richard Chambers Avatar asked Dec 19 '18 22:12

Richard Chambers


People also ask

Can memcpy overlap?

The CRT function memcpy doesn't support overlapping memory. The CRT provides an alternative to memcpy that does support overlapping memory: memmove .

What is the difference between memcpy and 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.

Does Memmove free memory?

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.


1 Answers

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.

like image 141
Cornstalks Avatar answered Oct 18 '22 04:10

Cornstalks