Is assigning a structure to the same address valid?

If there is something like this in my code:

void f(struct foo *x, struct foo *y) { *x = *y; // structure copy (memcpy?) } 

If x and y point to the same address , what happens?

Is this valid code, and what if the compiler converts the assignment into a memcpy call with potentially invalid operands (they are not allowed to overlap)?

[Yes, I know that I can use the "restriction" in this case, but the actual code that we found that made us consider this is automatically generated by the bison, so we were wondering if it should always be valid and whether the compiler should use memmove or something else that allows overlapping ..]

+4
source share
4 answers

[Yes, answering my own question, as I saw it, looking a bit at the standard and looking for more complex questions)

Actually, part of the answer to this answers the question. Are there any platforms where using a copy of the structure on fd_set (for select () or pselect ()) causes problems? (in this answer ) which I will be here:

One of the following:

...

the left operand has a qualified or unqualified version of the structure or type of association compatible with the type of law;

...

If the value stored in the object is read from another object that somehow overlaps the storage of the first object, then the overlap must be accurate and the two objects must have qualified or unqualified versions of a compatible type; otherwise, the behavior is undefined.

Therefore, as long as the pointers are the same (i.e. full overlap), then this will be fine. It still seems strange that the compiler sometimes calls memcpy, even though specc memcpy says that overlapping is not allowed. Perhaps the compiler knows more about the specific implementation of memcpy than the documentation eludes.

0
source

The designation of the structure is completely legal. Therefore, the compiler will generate the correct code (despite compiler errors).

+3
source

It looks absolutely fair to me. Yes, this will result in a memcpy type.

Two pointers to a struct like this should either be the same or not overlap at all. This way you can check if the pointers are equal earlier.

(You can, of course, trick your code into having a real overlap, but there must be a really special reason for this.)

+1
source

This is a valid code. The compiler cannot accept x! = Y, so it must use a secure memmove.

0
source

Source: https://habr.com/ru/post/1336120/


All Articles