[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [OT] C++ question re. dyn. mem.

On Mon, 04 Aug 2003 05:00:12 +0200, MJM wrote:

> Will the free store be properly maintained when the following is
> executed? // a simple object is defined typedef struct {
>    uint32_t	a;
>    uint64_t	b;
>    uint8_t	c;
> } t_my_type;

No typedef needed. This is C++.

struct t_my_type
	// blah

> // allocate some memory for an instance of this object t_my_type * p_a =
> (t_my_type) new t_my_type;

Similarly, the cast is superfluous, ugly, and in this case even wrong :-)
(you're missing a star).

t_my_type *p_a = new t_my_type; // what could be prettier?

> // change the way it is accessed to prove a point int * p_b = (int *)
> p_a;


> // p_a and p_b point to the same block of dyn. allocated memory;

Do they? Watch out for inheritance, user-defined casting operators and
other funny stuff. C++ adds a few new meanings to the () casting syntax.
In general, your assumption is _wrong_.

One should also note that the C-style casting operator is considered bad
style in C++. The "politically correct" way to rewrite your example is

int *p_b = reinterpret_cast<int *>(p_a);

That way, you're clearly stating the intent of the cast. It is up to your
compiler what it makes of this statement; the C++ standard doesn't cover
such abuse.

> // return the memory to free storage using the second pointer delete
> p_b;
> I think the free store will be maintained properly because there is a
> control block attached to the allocated block of storage that defines
> the length of the allocated memory.

No. You have to delete the original pointer (with the original type).
Everything else is undefined behaviour, i.e. it could work, it could leak
memory (completely or partly), it could crash, or even print "42". It
might even work sometimes, and fail mysteriously at other times.

(Please note that the rules are a bit different if the affected classes
are related in a inheritance hierarchy. This is not the case in your

Best Regards,   |   Hi! I'm a .signature virus. Copy me into
 Sebastian      |   your ~/.signature to help me spread!

Reply to: