简体   繁体   中英

memcpy not-POD objects leads to undefined behavior

In what situation ,an object of Class will guarantee to insert invisible data into an object ?

People usually said that it's not OK when using memcpy of copying objects instead of copy-assignment , sometimes the compiler will insert invisible data into the objects. so after memcpy ,the object memory layout maybe crashed.

If it contains virutal function,then it is not POD. But contains virtual ,the function may not crash ,it is not defined. Can someone give me any example that the memcpy is surely wrong.

Some people said that shared_ptr affect memcpy , I tried, but it doesn't crash

can someone write an test demo to prove it ?

shared_ptr is a good example: copying the object representation will give you a second pointer to the same object, but without incrementing the usage count. Once you've broken the invariant that the usage count must equal the number of pointers, you leave yourself open to undefined behaviour such as dereferencing dangling pointers, and deleting the same object twice:

shared_ptr<int> good(new int(42));
shared_ptr<int> evil;

memcpy(&evil, &good, sizeof evil); // Breaking invariant
good.reset();                      // Deletes object

*evil = 666;                       // BOOM! accesses deleted object
evil.reset();                      // BOOM! deletes object a second time.

You also mention virtual functions. These could cause problems if you copy the base sub-object of a derived class; the resulting object will (probably) point to the virtual table for the wrong class:

struct Base {
    virtual int f() {return 0;}
};

struct Derived : Base {
    int x;
    virtual int f() {return x;}
};

Base * good = new Derived;
Base evil;

memcpy(*evil, good, sizeof evil); // Base object with Derived vtable (probably)

evil->f(); // BOOM! probably accesses nonexistent member `x`

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