Click to See Complete Forum and Search --> : C++ new/malloc()


bwkaz
01-30-2002, 10:51 AM
Can you mix new and malloc()?

I have an array of object pointers, that I want to create first. Then I want to loop through the array, creating a new object of that class for each pointer, but calling a constructor with the loop index as a parameter. So I malloc()'ed the array, and am using new with the elements. Is this legal?

If you want/need code I can post it, but I don't have time at the moment.

Thanks

Stuka
01-30-2002, 11:31 AM
It's strongly recommended to NOT mix new and malloc(). What you should probably do in this case is use an STL vector in place of your array - this will dynamically resize as necessary, removing the need for malloc(). Then just create your objects and put them into the vector. Problem solved (and more easily, too).

tecknophreak
01-30-2002, 12:02 PM
i'd recommend never using malloc in C++ since there's new to do that work for you anyway.

also i'm agreeing with the vector usage. use stl as much as you can, it cuts down on coding time greatly. mmmmmmm...stl...

bwkaz
01-30-2002, 01:37 PM
Duh. I should have thought of that! *smack*

Thanks.

lazy_cod3R
01-30-2002, 06:03 PM
It's strongly recommended to NOT mix new and malloc().


Why is that ? what kind of errors can it cause.

Thanks....

sans-hubris
01-30-2002, 09:11 PM
Originally posted by lazy_cod3R:
<STRONG>Why is that ? what kind of errors can it cause.

Thanks....</STRONG>
It can cause major memory leaks, and objects won't necessarily be initialized right since malloc won't call the constructor. free doesn't call the destructor, and so not everything will be destroyed properly.

BTW, you can use new to call the constructor with a parameter, e.g.:

int *vars[COOLVAR];
for(int i=0; i&lt;COOLVAR; i++)
vars[i]=new int(i);

lazy_cod3R
01-30-2002, 10:11 PM
Oh ok, i understand what you mean now.

[ 30 January 2002: Message edited by: lazy_cod3R ]