Let’s say I have a first structure like this:
typedef struct {
int ivalue;
char cvalue;
}
Foo;
And a second one:
typedef struct {
int ivalue;
char cvalue;
unsigned char some_data_block[0xFF];
}
Bar;
Now let’s say I do the following:
Foo *pfoo;
Bar *pbar;
pbar = new Bar;
pfoo = (Foo *)pbar;
delete pfoo;
Now, when I call the delete operator, how much memory does it free?
sizeof(int) + sizeof(char)
Or
sizeof(int) + sizeof(char) + sizeof(char) * 0xFF
?
And if it’s the first case due to the casting, is there any way to prevent this memory leak from happening?
Note: please don’t answer “use C++ polymorphism” or similar, I am using this method for a reason.
The whole idea of such code is just undefined behavior. Don’t do it. What happens if someone overloads
operator newandoperator deletefor one struct and not for the other?The only legal way to do what you want is to inherit both structs from the comon base with a virtual destructors – then you will have proper defined behavior and no problems with deallocation.
However if
operator newandoperator deleteare not overloaded and both structs have trivial destructors it might just work allright on your implementation – the compiler will call::operator delete()that has one parameter – the address of the block and it will free exactly the right amount of memory. However don’t count on it – your code actually has undefined behavior.