I wanted to dig into how delete [] is knowing how many elements it has to erase from memory. I found num-elems-in-new-array-overalloc which is pretty clear. I know the implementation is compiler-specific but I just have the problem here to get the correct size of the array from the memory. I have no direct need of this functionality, just want to understand more clearly. As stated at num-elems-in-new-array-overalloc the size of an array can be stored by over-allocating memory.
char* tmp = (char*) operator new[] (WORDSIZE + n * sizeof(int));
Afterward, the pointer to the first array element is derived and the number of elements is stored at tmp
pointer.
int* p = (int*) (tmp + WORDSIZE);
*(size_t*)tmp = n;
My assumption is here that in case of decrementing the p
pointer two times (I assume WORDSIZE == sizeof(size_t)
with sizeof(size_t)== 8 Byte
) I should get the array size n
.
I made a small example over-allocation where I try to get the array size but somehow I get 49 instead of 40 as the array size in case of 10 array elements.
int* tmp = arr - 2;
std::cout << "Array size: " << *tmp << std::endl;
Address 0: 0x9efe70
Address 1: 0x9efe74
Address 2: 0x9efe78
Address 3: 0x9efe7c
Address 4: 0x9efe80
Address 5: 0x9efe84
Address 6: 0x9efe88
Address 7: 0x9efe8c
Address 8: 0x9efe90
Address 9: 0x9efe94
Array size: 49 <- In question
Probably my assumptions about WORDSIZE or the implementation in the compiler were wrong. What am I missing? I know about How does delete[] “know” the size of the operand array? but the answers are not really satisfying my question.
For those who have problems with repl.it, the full example:
#include <iostream>
void printMemoryLayout(int *arr, int n) {
for(int i = 0; i < n; ++i) {
std::cout << "Address " << i << ": " << &arr[i] << std::endl;
}
}
int n = 10;
int main() {
int* arr = new int[n];
printMemoryLayout(arr, n);
int* tmp = arr - 2;
std::cout << "Array size: " << *tmp << std::endl;
}
UPDATE: The compiler used was clang 7.0.0.3