Dynamically allocated structure and casting.

Posted by Simone Margaritelli on Stack Overflow See other posts from Stack Overflow or by Simone Margaritelli
Published on 2010-04-13T08:53:38Z Indexed on 2010/04/13 9:03 UTC
Read the original article Hit count: 351

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about memory-leaks