views:

136

answers:

4

I know that you have to do it like this:

int * p;
p = new int[10];

//use array

delete [] p;

Now my question is: Since it's not explicitly stated, how is it possible that the correct amount of memory is freed? Do the OS keep track of the allocated memory and its starting address?

+1  A: 

The runtime library will keep track of allocated blocks of memory. It's guaranteed to deallocate the block correctly, given the initial pointer returned by new.

While this can be implemented in the OS itself (theoretically), it normally isn't. What the OS keeps track of is the pages allocated to a process as a whole, not individual blocks allocated at this level of abstraction.

Mehrdad Afshari
+4  A: 

Yes, the OS (or more likely, the library) keeps track.

When you allocate memory, the OS creates a little header to your memory, which is usually just before your allocated memory - that is, at a slightly lower address by a few bytes.

When freeing memory, it takes the pointer that is freed, goes back a few bytes, and checks the structure that describes what was actually allocated, including the size of what was allocated.

Matthias Wandel
That is one way to do it.
Martin York
+1  A: 

It's completely implementation dependent. Much like regular malloc()/free(), there has to be some extra information saved by the system as you mentioned. In general, the call to malloc() or the new operator sets up a header structure in memory just before the the pointer it returns to you, so that later, when free() or the delete operator is called it can figure out what's up with the block of memory you handed it.

Carl Norum
A: 

It is depended on implementation, but I think that runtime library uses some sort of memory allocation tables to keep track of allocated blocks.

Kirill V. Lyadvinsky