Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the delete in C++ know how many memory locations to delete

how does the delete operator work? Is it better then free()?. Also if u do ptr=new char[10], then delete using delete ptr, how does the pointer know how many locations to delete.

like image 719
shreyasva Avatar asked Feb 24 '10 17:02

shreyasva


3 Answers

There is only delete operator, free exist only as function. Under C++, you are encouraged to use new/delete over malloc()/free().


There is an internal "magic" in delete operator. When an array is created with new[], the size of array is stored in the metadata at the memory block. delete[] makes use of that information.

All this is of course compiler-, OS-, optimizer- and implementation-dependent.

like image 59
Vlad Avatar answered Oct 12 '22 23:10

Vlad


if you do a non-array type:

T t = new T;
// ...
delete t;

It will know how much to delete because it knows how big a T is. If you do an array:

T t* = new T[10];
// ...
delete [] t;

It will lay down some extra info with the allocation to tell it how much to delete. Note, we use delete [] t with the extra [] in there to tell it it's an array. If you don't do that it will think it's just a T and only free that much memory.

Always use delete if you use new and free if you use malloc. new does 2 things first it allocates the memory, then it constructs the object. Similarly delete calls the destructor and then frees the memory. malloc\free only deal with the memory allocation and deallocation.

like image 26
Matt Price Avatar answered Oct 13 '22 00:10

Matt Price


  1. In C++, a constructor is called using new, but not when using malloc. Similarly a destructor is called when using delete, but not when using free.

  2. If you have new-ed an array using MyClass* x = new MyClass[25], then you need to call delete[] x, so that they system knows that it's deleting (and destructing) a group of objects instead of a single one.

like image 44
Joel Avatar answered Oct 12 '22 23:10

Joel