Home > other >  Byte allocation different for dynamic vs. static char array of same size?
Byte allocation different for dynamic vs. static char array of same size?

Time:11-03

So, I ran this code in my IDE. Can anyone explain the reason why the same amount of memory isn't allocated to both of these arrays when they should be the same size?

char* dynamicCharArr = new char[15]; //allocates 8 bytes
cout << sizeof(dynamicCharArr) << endl;

char staticCharArr[15]; //allocates 15 bytes
cout << sizeof(staticCharArr) << endl;

CodePudding user response:

new[] returns a pointer to the memory it allocates. You are printing the size of the pointer itself, not the size of the allocated memory being pointed at.

There is no way for sizeof() to query the size of that allocated memory. If you pass in the pointer itself, you get the size of the pointer. If you pass in the dereferenced pointer, you get the size of 1 element of the array, not the whole array. In that latter case, you would have to multiply that size by the element count that you pass to new[].

In both examples, the amount of memory accessible to your code is sizeof(char) * 15. But you simply can't obtain that value from a pointer alone, which is why sizeof(dynamicCharArr) doesn't work. In a fixed array, the size is part of the array's type, which is why sizeof(staticCharArr) does work.

However, note that the physical memory allocated by new[] for a dynamic array will always be slightly larger than the memory used by a fixed array of the same element count, because new[] allocates additional internal metadata that is used by delete[], and even the memory manager itself. That metadata will include (amongst whatever else the memory manager needs internally, like debug info, block tracking, etc) the number of elements that new[] allocated, so delete[] knows how many elements to destroy. But sizeof() doesn't know (or care about) that metadata.

CodePudding user response:

sizeof(dynamicCharArr) gets you the size of the pointer to the char array. Try sizeof with a dynamic char array of a different size. It will be the same (on the same system).

  • Related