Advertisement

C/C++ new and delete vs. malloc and free

Started by February 12, 2002 09:18 AM
25 comments, last by Fundy Glostna 22 years, 7 months ago
What I want to know is simply this: can I use the c++ "new" and "delete" operations with C structs? Or can I only do so with C++ classes? Also, I''m kind of confused about how new and delete differ from "malloc" and "free". Are they better and some way? Do they do the same things?
No, Canadians DON'T all live in igloos. They live in one BIG igloo!
Hey hey,

You can use new and delete to create C structs and the like (as structs are a data type, just like ints and longs etc.). If you''ve been nice to the C++ compiler, you won''t have any methods inside structs. Rather, you''ll have them in classes. As such, no constructor/destructor code will be called. Biggest mistake (at least with MSVC++ ) you can make is trying to free() a block of memory you allocated with new[], or delete[]ing a block of memory you allocated with malloc/calloc/etc.

I''m not sure about malloc()ing classes ... that almost certainly won''t be a good idea, as the constructor won''t be called (unless this is done explicitly, I suppose?). You should ALWAYS use new/new[]/delete/delete[] when dynamically allocating classes, just to be safe. I couldn''t imagine any major difference in functionality and/or speed between new/malloc and delete/free, except for the fact that it would be easier to use new and delete all the time

Tom
refrain_from_stupidity( &me );
Advertisement
From what i remember new & delete call the constructor/destructor. So malloc wouldn''t (or should i say shouldn''t?) work with classes.
I use malloc()/free() for strings, arrays, and other data of non uniform size, mainly because I learned to use them when I learned c, and I can use realloc() to change their size.

I always use new/delete for classes, because I don''t think that free() would call the objects destructor.

You can use new and delete with C structures. You should use new and delete in c++ because it''s type safe. Using malloc you need to force a type on the object because it returns a void pointer, and you can''t assign that to other types. You also don''t have to figure out the size of what you''re creating.

Would you rather write ''int* array = (int *)malloc(sizeof(int)*50);'' or ''int* array = new int[50];''

Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.
do you mean something like:
  struct SomeStruct{int SomeInt;char SomeString[1024];SomeStruct *pNext;};SomeStruct *sStruct = new SomeStruct;sStruct->pNext = new SomeStruct;...delete sStruct->pNext;delete sStruct;  


Yes its completelly valid.

I''ve heard that internally new and delete use malloc and free, to me new and delete are better because you dont have to worry about typecasts, and sizeof()''s, also, new is OOP, when you new a class instance new calls the constructor of the class, and delete the destructor, so if you are using dinamicaly allocated objects, new and delete is what you should use.

new and delete will always make sure that the constructor and destructor is called for classes (and structs if they have them). For built-in data types and C structs, there is no need to use new and delete over malloc and free, except for the fact that new and delete might be easier to use. In fact, on many compilers, new and delete just call malloc and free to allocate memory, so there is usually no difference aside from the constructor/destructor calls.
Advertisement
The MSDN has an example of overloading the new and delete operators, and their code uses malloc in the overloaded new and free in the overloaded delete. It''s like this:

  void* operator new ( size_t Size ){    return malloc( Size );} void operator delete ( void* Data ){    if( Data ) free( Data );}  

The constructors and deconstructors are called automatically, you don''t do that. Anyway I overloaded these operators to write a very detailed memory log. Here''s an excerpt:
08:57:35pm - new WORD[] (23814)           @ Vista::CompileHMWorld()         [total 434994 bytes in 23 object(s)]08:57:35pm - del BYTE[] (12288)           @ Vista::CompileHMWorld()         [total 422706 bytes in 22 object(s)]08:57:35pm - new Geometry (112)           @ Renderer::AddGeometry()         [total 422818 bytes in 23 object(s)]08:58:16pm - del Keyboard (3080)          @ Magic::Shutdown()               [total 419738 bytes in 22 object(s)] 

It is so wonderful for debugging. And I know for a fact that there are no memory leaks.

~CGameProgrammer( );

~CGameProgrammer( ); Developer Image Exchange -- New Features: Upload screenshots of your games (size is unlimited) and upload the game itself (up to 10MB). Free. No registration needed.
ok I just ran a test, this is not intended to argue with anyone nor to start any holy wars, I just wanted to make sure what really goes on:

this program:
  #include <stdio.h>#include <malloc.h>class CTest{public:  CTest()  {    printf("Constructor Called.\r\n");  };  ~CTest()  {    printf("Destructor Called.\r\n");  };};int main(){  CTest *test = NULL;  printf("Using new and delete:\r\n\r\n");  test = new CTest;  delete test;  printf("\r\nUsing malloc and free:\r\n\r\n");   test = NULL;  test = (CTest *) malloc(sizeof(CTest));  free(test);};  


has this output:
  Using new and delete:Constructor Called.Destructor Called.Using malloc and free:  


my conclusion, unless you are overloading new and delete, malloc and free wont call constructors, destructors.

I compiled with Mingw32, GCC 2.95.2, if you have different results with other compilers the outcome would be nice to know.

Yeah, you didn''t need to run a test program to find that out... malloc and free just allocate and deallocate memory. They don''t call any constructors. They can''t because they don''t even know what variable type they''re allocated. The new and delete operators automatically call the constructors and deconstructors.

~CGameProgrammer( );

~CGameProgrammer( ); Developer Image Exchange -- New Features: Upload screenshots of your games (size is unlimited) and upload the game itself (up to 10MB). Free. No registration needed.
Well, I ran the test because I have a tendency to say things(based on supositions) just to stand corrected in a few posts after mine

anyway the test should leave anyone without any doubt.

This topic is closed to new replies.

Advertisement