Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » C++ question... malloc or new

This thread is locked; no one can reply to it. rss feed Print
 1   2 
C++ question... malloc or new
Dario ff
Member #10,065
August 2008
avatar

I have always been wondering of this while programming. ???

I use C++, but i like using the malloc function for allocating my objects, but i don´t know difference between using new and malloc (differences on runtime process, not writing).

so, my question is, if i use C++, should i always use the new function or i can use malloc as well?

I would really like an answer to this, since I always had this doubt.

Thnx for reading... ;D

TranslatorHack 2010, a human translation chain in a.cc.
My games: [GiftCraft] - [Blocky Rhythm[SH2011]] - [Elven Revolution] - [Dune Smasher!]

bamccaig
Member #7,536
July 2006
avatar

AFAIK, malloc just allocates memory. The new keyword allocates memory and initializes the object (i.e. calls the constructor) AKA instantiates an object. It's the difference between having an instance of Foo and having enough memory for an instance of Foo. If you use malloc to create a Foo, then what you really have is a pointer to sizeof(Foo) bytes of garbage, not a Foo. I assume for C++ code you should be using new/delete and for C-only code using malloc/free.

Dario ff
Member #10,065
August 2008
avatar

oh ok, but i don´t use too much constructors myself, so i think i will stick with malloc. thnx

TranslatorHack 2010, a human translation chain in a.cc.
My games: [GiftCraft] - [Blocky Rhythm[SH2011]] - [Elven Revolution] - [Dune Smasher!]

Audric
Member #907
January 2001

Quote:

if i use C++, should i always use the new function

IMO, when you're using classes, you should always use new and delete.
-> You can't pick the wrong size on allocation,
-> If you later put some code in the constructor and/or destructor, it will be called.

OICW
Member #4,069
November 2003
avatar

I'd reccomend using new and delete if you use C++. If you want complete control like with malloc, I remember there's something called allocator class, which should provide you with malloc functionality.

And as far as objects go, you should use new and delete any time.

[My website][CppReference][Pixelate][Allegators worldwide][Who's online]
"Final Fantasy XIV, I feel that anything I could say will be repeating myself, so I'm just gonna express my feelings with a strangled noise from the back of my throat. Graaarghhhh..." - Yahtzee
"Uhm... this is a.cc. Did you honestly think this thread WOULDN'T be derailed and ruined?" - BAF
"You can discuss it, you can dislike it, you can disagree with it, but that's all what you can do with it"

OnlineCop
Member #7,919
October 2006
avatar

I'm in favor of 'new' and 'delete' because of the ability of C++ to overload functions. If your class inherits any others, it's very possible that those other classes could have constructors/destructors.

'malloc' and 'free' have their place for C, but for C++, everyone who has ever discussed this topic with me has strongly opted for 'new' and 'delete'.

Mokkan
Member #4,355
February 2004
avatar

You should use new and delete with classes at least. I'm not sure why you'd use malloc over new in any other case either...

EDIT: Wow, I got way beaten.

bamccaig
Member #7,536
July 2006
avatar

samo the thief said:

oh ok, but i don´t use too much constructors myself, so i think i will stick with malloc. thnx

Keep in mind that when you say...
Foo* foo = (Foo*)malloc(sizeof(Foo));
The members of the Foo that foo points to are garbage. They can be anything; whatever was in that block of memory before the OS allocated it to your program. This can introduce subtle bugs and/or odd behavior on anything dependent on those values being within some constraint. I haven't done a lot of C coding, but what I have done always had me zeroing newly allocated memory (i.e. memseting the newly allocated memory to 0s).

A constructor goes one step further and sets all members to known default values. Even in C, you can use a constructor concept to initialize a structure, either by wrapping the creation into a function (e.g. create_foo) or by passing the existing pointer into a function (e.g. init_foo) and setting all members to known default values. Either way, you may need to be careful if you're just going to leave it as garbage.

Unless your application requires the finite optimization of not writing unnecessarily to those memory blocks (and in 99.999999999% of cases it won't), I would recommend you either zero the memory or call some kind of initializer/constructor. C++ makes this an easy and intuitive process so why fuck with that? :)

Dario ff
Member #10,065
August 2008
avatar

i was talking about malloc because I learned some c way back ago, but now i started using C++, and i got that little doubt. well, suppose I´m going to have a nice day today with replacing some part of my code XD

TranslatorHack 2010, a human translation chain in a.cc.
My games: [GiftCraft] - [Blocky Rhythm[SH2011]] - [Elven Revolution] - [Dune Smasher!]

Kitty Cat
Member #2,815
October 2002
avatar

Quote:

The members of the Foo that foo points to are garbage.

Also note that if your class contains other classes (eg. std::string, std::vector), using malloc will NOT initialize those object properly and can crash when you try to use them.

--
"Do not meddle in the affairs of cats, for they are subtle and will pee on your computer." -- Bruce Graham

aj5555
Member #9,033
September 2007

there are other alternatives.

Speedo
Member #9,783
May 2008

IMO, it's utterly foolish to write C++ code with malloc/free. If you mix them with new/delete in your code, you risk quite a bit of confusion for yourself or anyone else later on (do I need to free this pointer or delete it? can't interchange the two). If you go entirely malloc/free you're begging for problems initializing C++ objects. And the big question is... what is malloc doing for you that new is incapable of doing?

Onewing
Member #6,152
August 2005
avatar

Quote:

there are other alternatives.

Sounds like you're offering to sell him watches in a dark alley...

I personally love new and delete and said goodbye to malloc/free a while ago. The only times I have any difficulty (have to refresh myself) is when I create a multidimensional array with new.

------------
Solo-Games.org | My Tech Blog: The Digital Helm

Tobias Dammers
Member #2,604
August 2002
avatar

Multidimensional arrays in C are a brain-wrecking piece of crap anyway.
With all the template power C++ bestowes upon us, might as well create a template that encapsulates a plain 1d array (or an array of arrays if you prefer that) into a nice class that behaves like an n-dimensional array. While you're at it, might as well add bounds checking a la std::vector. Only downside is you call a getter method instead of using the [] operator, but that's just syntactic sugar IMO.

---
Me make music: Triofobie
---
"We need Tobias and his awesome trombone, too." - Johan Halmén

Timorg
Member #2,028
March 2002

if your array is of pointers, or they are all positive integers, you could use the [] operator and return -1 or NULL

____________________________________________________________________________________________
"c is much better than c++ if you don't need OOP simply because it's smaller and requires less load time." - alethiophile
OMG my sides are hurting from laughing so hard... :D

Tobias Dammers
Member #2,604
August 2002
avatar

Yes and no.
Operator[] is supposed to return a reference, and if you're out of bounds, you cannot do this (though throwing an exception would be a proper way of handling this I guess).

---
Me make music: Triofobie
---
"We need Tobias and his awesome trombone, too." - Johan Halmén

axilmar
Member #1,204
April 2001

Quote:

so, my question is, if i use C++, should i always use the new function or i can use malloc as well?

Forget malloc and free, use new.

Don't use delete, use boost::shared_ptr. You might be a newbie, but you will regret it later if you don't do so. It takes a while to learn boost, but it pays off hugely.

Tobias Dammers
Member #2,604
August 2002
avatar

I say, manual memory management builds character.

---
Me make music: Triofobie
---
"We need Tobias and his awesome trombone, too." - Johan Halmén

Trezker
Member #1,739
December 2001
avatar

#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<Myclass> MyclassPtr;
MyclassPtr myclassinstance(new Myclass);

Voila, instant garbage collection! ;)

I'm rather dissatisfied with the naming of shared pointer types though.
Now I'm using ClassnamePtr, and ClassnameWeakptr but I don't feel they work well with my coding standard over all. I have Names_with_underscore if there's multiple words, but the shared pointers get CamelCase.

Any tips?

bamccaig
Member #7,536
July 2006
avatar

Trezker
Member #1,739
December 2001
avatar

Maybe you're right...

amber
Member #6,783
January 2006
avatar

Quote:

what is malloc doing for you that new is incapable of doing?

realloc?

(I actually don't know. I'd be curious if any people more knowledgable in C++ could weigh in...)

Speedo
Member #9,783
May 2008

Quote:

realloc?

(I actually don't know. I'd be curious if any people more knowledgable in C++ could weigh in...)

It seems to me like the primary use of realloc (at least in C++) would be to resize a dynamic array. Of course, 98% of C++ programmers would then tell you to use vector or another STL container, but even if you insisted on using arrays you could duplicate realloc with a little template magic:

template<typename T>
T* ReAllocate(T* ptr, size_t curElements, size_t newElements)
{
  assert(ptr);
  T* nuptr = new T[newElements];  
  memcpy(nuptr, ptr, sizeof(T) * ((curElements < newElements) ? curElements : newElements));
  delete [] ptr;
  return nuptr;
}

axilmar
Member #1,204
April 2001

The memcpy you do is bad, very bad.

You should never do that with C++ objects. You should always use the assignment operator to copy the data.

Matt Smith
Member #783
November 2000

Quote:

If you mix them with new/delete in your code, you risk quite a bit of confusion for yourself or anyone else later on (do I need to free this pointer or delete it? can't interchange the two)

IMO, That's a sound reason for sticking to C. The raison d'etre for C++ is that the OOP model is standard. For this reason alone, you should use new/delete when writing classes.

 1   2 


Go to: