Money said:
If I allocate memory like this
int *ptr = new int[1];
Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.
For Plain Old Datatype (POD) like an int, it likely not to
matter. delete[] also destructs each of the elements of the
array. If you use 'delete', you'll bypass destructing the
elements of the array.
Not necessarily true. An array may be allocated differently than a
single object (and we're not talking about construction/destruction).
I could see one potential implementation as follows:
- When allocating memory for a single object, allocate sizeof(int) +
sizeof(object). Write the size of the object in the first sizeof(int)
bytes, invoke the constructor on the sizeof(object) bytes, return a
pointer to the object. (Perhaps there's customized allocators for
different-sized objects)
- When allocating memory for an array of objects, allocate sizeof(int) +
sizeof(int) + arraysize * sizeof(object). Write the arraysize in the
first sizeof(int) bytes, write sizeof(object) in the second sizeof(int)
bytes, invoke the constructor on each of the sizeof(object) bytes.
Return a pointer to the first object.
- When using delete, invoke the destructor on the sizeof(object) bytes
starting at the pointer, back up sizeof(int) bytes, hand this pointer
back to wherever the memory came from (perhaps some global
allocator/deallocator)
- When using delete[], back up sizeof(int) + sizeof(int). Copy out the
first sizeof(int) as the number of objects, copy the 2nd sizeof(int) for
the object size. Loop over each of the sizeof(object) bytes (starting
from the _end_ of the array) and invoke the destructor on each object in
turn. Finally hand the pointer - sizeof(int) - sizeof(int) back to
wherever the memory came from.
As a result, if you allocate with:
int * p = new int[1];
You get 12 bytes allocated, starting at p - 8. (Let's assume no padding
and sizeof(int) == 4)
When you call:
delete p;
You end up attempting to hand p - 4 back to the OS. Since it didn't
allocate that pointer, who knows what it's going to do. And in the
theoretical case where different-sized allocations come from different
pools, this memory block would be handed back to the wrong pool too (say,
the 8-byte allocator instead of the 12-byte allocator).