Skip to main content
gamedev.net
🔒 Locked

Memory Allocation Problem

Started by robirt 4 replies 1.2k views
Original Post
robirt
robirt
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?
Rodger
Sneftel
Sneftel
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.
robirt
robirt
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?
Rodger
robirt
robirt
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]
Rodger
Sneftel
Sneftel
Trying to use a custom allocator? Look into "placement new".
Raloth
Raloth
The compiler does give you a default constructor if you do not give it one.

[edited by - Raloth on August 8, 2003 12:58:00 AM]
____________________________________________________________AAAAA: American Association Against Adobe AcrobatYou know you hate PDFs...

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.