+ 5
How to get the size from an array that allocated on the heap?
Here is the code.. https://code.sololearn.com/cTwT4CDJxTZA/?ref=app
10 Réponses
+ 7
A lot of stuff going on when the compiler asks the OS to allocate some amount of memory for some dynamic storage. For example, when you ask for 2 integer blocks dynamically as
int *arr = new int[2];
It's not simply `sizeof(int) * 2` bytes. For the sake of reclaiming the memory later on and keeping track of allocated blocks, the OS adds some additional housekeeping information to both sides of each newly allocated block (in above example, 2 cells) like this
##############
heap info
##############
pointer to the next heap block
##############
pointer to the prev heap block
##############
...
##############
Guard bytes (buffer overrun indicators)
##############
32-bit integer (actual accessible data)
##############
32-bit integer (actual accessible data)
##############
Guard bytes (buffer overrun indicators)
##############
...
##############
Housekeeping info
##############
Housekeeping info
##############
Housekeeping info
##############
...
Therefore, neither you can get the size of the actual data (just the size of a pointer to the first allocated cell) nor can't you manipulate the size of it or delete the entire blocks manually without calling `delete[] arr`.
+ 4
Good idea ~ swim ~, thanks for tell me.
+ 3
It's not possible! Nobody is preventing you from reading past the array boundary and doing `myhArray[99999]` in C++. (Though your program will probably crash)
You either have to keep track of the size yourself, or use something like std::vector instead of arrays, which do all the hard work for you.
+ 3
Schindlabua and C++ Soldier (Babak) thanks for your explanation about it.
+ 3
~ swim ~ dependent? You mean like the size of an integer depend upon the compiler and processor?