Freitag, 25. April 2008

memcpy an object

Some days ago we stumbled upon a problem which first seemed unaccountable: After adding a virtual function to a class, another of our programs which (at first sight) should not have been affected by this change, simply: crashed.
After some analysing and hard thinking we realised what the problem was: This program used an array of objects of this class to which the virtual function was added.
That of course was not the problem, but at one place another object of this class was created and then the data of this object copied into the array.
That was the idea. And it worked ok as long as the class did not contain any virtual function.
A class without virtual functions can be treated like a class, and its data can be copied from one object to another with memcpy without any problem (as long as the class does not contain any pointers, but that's another story).
By adding a virtual function a 'virtual function table' is added to the each object which is used to determine the function address to use when the function is called. Using memcpy on such objects copies the data and the virtual function table from one object to another. This may even work as long as both objects exist, but when the source object is deleted, the object where the data was copied to contains pointers in the virtual function table which point to anything but not valid function adresses anymore. Trying to call a virtual function then leads to a crash.

Keine Kommentare: