Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

malloc vs calloc and new

Status
Not open for further replies.

deano99

Programmer
Joined
Oct 30, 2003
Messages
1
Location
GB
I'm trying to allocate memory to a void pointer and then cast it to a class, which contains a vector member variable. When I try and use the vector member function push_back, my program crashes if I use malloc to allocate memory, but not when I use calloc or new,

Any ideas why malloc causes a problem?
 
> Any ideas why malloc causes a problem?
new specifically calls the constructor for your class, so should be the vastly preferred method of dynamically creating instances of your class.
Additionally, using new means that you don't need an explicit cast of the returned pointer.

calloc is like malloc, except that all the memory allocated is initialised to zero. This is probably enough for your class, but should not be relied on.

malloc just leaves the memory containing whatever junk was there from last time, and is certainly illegal data as far as your class is concerned.


--
 
As Salem said with the addition that if you have virtual methods in the virtual table of class it will most certainly be screwed up unless you use new that constructs it properly.

>Any ideas why malloc causes a problem?

It is not designed for C++ classes.

/Per

"It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure."
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top