Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use malloc/free, when we have new/delete?

What is the use of malloc and free when we have new and delete in C++. I guess function of both free and delete is same.

like image 881
Parag Avatar asked Apr 02 '12 07:04

Parag


People also ask

What is the difference between malloc() and free() in C++?

We use new and delete operators in C++ to dynamically allocate memory whereas malloc () and free () functions are also used for the same purpose in C and C++. The functionality of the new or malloc () and delete or free () seems to be the same but they differ in various ways.

Is there a memory leak when using malloc() and free()?

new calls a constructor, malloc () does not. delete calls a destructor, free () does not. If the class in question allocates memory internally, then yes, you are likely to encounter a memory leak.

What is the behavior of malloc with delete in C++?

Behaviour of malloc with delete in C++. int *p=(int * )malloc(sizeof(int)); delete p; When we allocate memory using malloc then we should release it using free and when we allocate using new in C++ then we should release it using delete. But if we allocate memory using malloc and then use delete, then there should be some error.

What is the use of malloc?

malloc/ free Allocate / release memory Memory allocated from 'Heap'. Returns a void*. Returns NULLon failure. Must specify the size required in bytes. Allocating array requires manual calculation of space. Reallocating larger chunk of memory simple (no copy constructor to worry about). They will NOTcall new/ delete.


2 Answers

They're not the same. new calls the constructor, malloc just allocates the memory.

Also, it's undefined behavior mixing the two (i.e. using new with free and malloc with delete).

In C++, you're supposed to use new and delete, malloc and free are there for compatibility reasons with C.

like image 158
Luchian Grigore Avatar answered Sep 21 '22 11:09

Luchian Grigore


In C++, it is rarely useful that one would use malloc & free instead of new& delete.

One Scenario I can think of is:

If you do not want to get your memory initialized by implicit constructor calls, and just need an assured memory allocation for placement new then it is perfectly fine to use malloc and free instead of new and delete.

On the other hand, it is important to know that mallocand new are not same!
Two important differences straight up are:

  • new guarantees callng of constructors of your class for initializing the class members while mallocdoes not, One would have to do an additional memset or related function calls post an malloc to initialize the allocated memory to do something meaningful.

  • A big advantage is that for new you do not need to check for NULL after every allocation, just enclosing exception handlers will do the job saving you redundant error checking unlike malloc.

like image 40
Alok Save Avatar answered Sep 20 '22 11:09

Alok Save