C++ doesn’t tell you the size of a dynamic array. But why?

It’s a follow on from the fundamental rule of “don’t pay for what you don’t need”. In your example delete[] a; doesn’t need to know the size of the array, because int doesn’t have a destructor. If you had written:

std::string* a;
a = new std::string[n];
...
delete [] a;

Then the delete has to call destructors (and needs to know how many to call) – in which case the new has to save that count. However, given it doesn’t need to be saved on all occasions, Bjarne decided not to give access to it.

(In hindsight, I think this was a mistake …)

Even with int of course, something has to know about the size of the allocated memory, but:

  • Many allocators round up the size to some convenient multiple (say 64 bytes) for alignment and convenience reasons. The allocator knows that a block is 64 bytes long – but it doesn’t know whether that is because n was 1 … or 16.

  • The C++ run-time library may not have access to the size of the allocated block. If for example, new and delete are using malloc and free under the hood, then the C++ library has no way to know the size of a block returned by malloc. (Usually of course, new and malloc are both part of the same library – but not always.)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)