vmahth1
vmahth1

Reputation: 203

c++ struct pointer to adress struct error CDCDCD

struct XYZ {
    XYZ *adress;
};

XYZ *Ex;
int main() {
    Ex = new XYZ[3];
    Ex->adress = (++Ex);
    cout << Ex->adress << endl;
    Ex->adress = (++Ex);
    cout << Ex->adress << endl;
    Ex->adress = (--Ex)->adress;
    cout << Ex->adress << endl;    

Output:

0105E424        
0105E428
0105E424
struct XYZ {
    XYZ *adress;
};

XYZ *Ex;

void copy_adress(XYZ *Ex) {
    Ex->adress = (++Ex);
}

int main() {
    Ex = new XYZ[3];
    copy_adress(Ex);
    cout << Ex->adress << endl;
    Ex->adress = (++Ex);
    cout << Ex->adress << endl;
    Ex->adress = (--Ex)->adress;
    cout << Ex->adress << endl;

Output:

CDCDCDCD
00A3E53C
CDCDCDCD

Can you tell me why this is happening, and how I can fix it?

Upvotes: 1

Views: 168

Answers (2)

M.M
M.M

Reputation: 141628

(This is supplemental information, cigien answered the main question)

There was some speculation in comments about the sequencing of Ex->adress = (++Ex). Since C++17, the right operand of = is sequenced-before the left operand. And since C++11 both operands are sequenced-before the assignment.

So ++Ex is completed, and then the new value of Ex is used for the computation Ex->address. Prior to C++17 this was undefined behaviour.

The second code example does have UB but for a different reason: reading uninitialized memory:

Upvotes: 1

cigien
cigien

Reputation: 60258

Pointers behave just like regular objects when you copy them, or pass them to a function. Changes to the copy are not reflected in the original. To make the changes in a function visible, you need to take it by reference:

void copy_adress(XYZ *&Ex) {
   Ex->adress = (++Ex);
}

Now, the 2 versions are equivalent.

Upvotes: 4

Related Questions