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

Scooter
  • 6,802
  • 8
  • 41
  • 64
Betamoo
  • 14,964
  • 25
  • 75
  • 109
  • It's not the right way to create an array, because you assigned it to an int and then trying to delete an int. It should be int *a = new int[size]; – fingerprint211b Apr 28 '10 at 09:41

3 Answers3

2

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.

Paul R
  • 208,748
  • 37
  • 389
  • 560
Gene Vincent
  • 5,237
  • 9
  • 50
  • 86
  • What if I had allocated size bigger than a memory chunk? Will it delete the 1st memory chunk pointed to only? – Betamoo Apr 28 '10 at 09:49
  • @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 Apr 28 '10 at 09:49
  • 1
    ... and when you call delete[] it also calls the appropriate number of destructors. – Viktor Sehr Apr 28 '10 at 11:19
2

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.

Puppy
  • 144,682
  • 38
  • 256
  • 465
0

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
  • 256,549
  • 94
  • 388
  • 662