views:

114

answers:

3

Is this the right way to use delete[] operator?

int* a=new int[size];
delete[] a;

If yes, Who (compiler or GC or whoever) will determine the size of the newly created array? and where will it store the array size?

Thanks

+2  A: 

For each chunk of memory allocated, the memory allocator stores the size of the chunk (that's why it is inefficient to allocate many small blocks compared to one big one for example). When delete frees the memory, the allocator knows how large the memory chunk is the pointer points to.

Gene Vincent
What if I had allocated size bigger than a memory chunk? Will it delete the 1st memory chunk pointed to only?
Betamoo
@Betamoo: Either it will allocate enough memory or throw the exception to indicate that it can't. So you can't "free less" - the memory manager will decide on its own.
sharptooth
... and when you call delete[] it also calls the appropriate number of destructors.
Viktor Sehr
A: 

By the way, every time you are tempted to write new T[size], you should probably use std::vector<T> instead. Using local pointers to dynamic arrays, it's simply too hard to guarantee proper memory release in the case of exceptions being thrown.

FredOverflow
+1  A: 

Technically, that usage is perfectly valid. However, it's generally a bad idea to go newing arrays like that, and you should use a std::vector.

DeadMG