Archived

This topic is now archived and is closed to further replies.

robirt

Memory Allocation Problem

Recommended Posts

Ok, i have a class called TCPCLIENT and i have done this: TCPCLIENT *tcpClient; tcpClient=new TCPCLIENT; And that works fine. But when i try this: TCPCLIENT *tcpClient; tcpClient=(TCPCLIENT *)malloc(sizeof(TCPCLIENT)); my program gets an error and quits as soon as i try to access tcpClient. I don''t have a constructor for TCPCLIENT, so i was wondering why the different calls even make a difference. I was told that new is just runs the constructor and then basically does malloc. BTW, TCPCLIENT is derived from CLIENT, which also has no constructor. Any ideas?

Share this post


Link to post
Share on other sites
Mixing malloc and new can cause problems under certain architectures; most runtime libraries actually do not use malloc (since they can use inlining with a constant size instead). Also, even if you don''t think there''s a constructor, often there is one (the compiler generates one which constructs all class members, as well as setting the vtable). Bottom line: malloc() has no place in C++. Never ever use it.


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
ok, now i overloaded the new operator like this:
inline void* operator new(unsigned int nSize)
{
return malloc(sizeof(TCPCLIENT));
}

and it works... so, im confused.
Could it have anything to do with the fact that TCPCLIENT is from a lib and being allocated in the exe code?

Share this post


Link to post
Share on other sites
when i overload new, will it still execute that constructor automatically?
The reason im doing this is because I was using a custom memory allocator, and after it didnt work, i tried using new and malloc, to see if they would work. I think i heard that before that the complier automatically makes a constructor.
so im thinking i can overoad new to use my custom allocator, if that will work.

[edited by - robirt on August 8, 2003 6:39:45 PM]

Share this post


Link to post
Share on other sites