Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete & new in c++

Tags:

c++

This may be very simple question,But please help me.

i wanted to know what exactly happens when i call new & delete , For example in below code

char * ptr=new char [10];

delete [] ptr;

call to new returns me memory address. Does it allocate exact 10 bytes on heap, Where information about size is stored.When i call delete on same pointer,i see in debugger that there are a lot of byte get changed before and after the 10 Bytes.

Is there any header for each new which contain information about number of byte allocated by new.

Thanks a lot

like image 362
Satbir Avatar asked Apr 13 '10 10:04

Satbir


4 Answers

Do it allocate exact 10 bytes

That's implementation dependant. The guarantee is "at least 10 chars".

Where information about size is stored?

That's implementation dependant.

Is there any header for each new which contain information about number of byte allocated by new?

That's implementation dependant.

By "that's implementation dependant" I mean it's not defined in the standard.

like image 157
Johann Gerell Avatar answered Sep 24 '22 23:09

Johann Gerell


That's all up to the compiler and your runtime library. It's only exactly defined what effects new and delete have on your program, but how exactly these are acieved is not specified.

In your case it seems like a little more memory than requested is allocated and it will probably store management information like the size of the current chunk of memory, information about adjacent areas of free space or information to help the debugger try to detect buffer overflows and similar problems.

like image 32
sth Avatar answered Sep 21 '22 23:09

sth


It is completely implementation-dependent. In general case you have to store the number of elements elsewhere. The implementation must allocate enough space for at least the number of elements specified, but it can allocate more.

like image 40
sharptooth Avatar answered Sep 23 '22 23:09

sharptooth


Is there any header for each new which contain information about number of byte allocated by new.

That's platform dependent but yes, on many platforms there are.

like image 29
sepp2k Avatar answered Sep 20 '22 23:09

sepp2k