Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you mix free and constructor in C++? [duplicate]

Possible Duplicate:
Is there any danger in calling free() or delete instead of delete[]?

I was reading this question:
In what cases do I use malloc vs new?

Someone raised that one reason to use malloc was if you were going to use free.

I was wondering: Is it valid to mix a free call and a constructor initialization in C++?

i.e.

Can I say:

my_type *ptr = new my_type;
free(my_type);

Is that somehow invalid or worse than:

my_type *ptr = new my_type;
delete my_type;

other than the fact that it's not c++ish?

Likewise, could you do the opposite? Can you say

my_type *ptr = (my_type *)malloc(sizeof(my_type));
delete my_type;

Please merge if this is a duplicate, I searched but didn't see a question along this lines exactly about malloc/delete/new/free asked.

like image 397
Jason R. Mick Avatar asked Nov 23 '25 09:11

Jason R. Mick


1 Answers

No it is invalid. There is no guarantee that new will use malloc or delete will use free.

Moreover, using free instead of delete will skip my_type's destructor. If my_type itself is holding some resources, those will be leaked. Similarly, malloc will skip the constructor so the variable may be in an invalid state.

like image 190
kennytm Avatar answered Nov 24 '25 23:11

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!