Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of array (new[])

In debug heap I can get size of array, which was created by new[]:

int size = *((int *)((char *)ptr - 16));

It is working correctly if the size of the array is less than 28 (but I don't know why? 0_0).

Does this trick working in release mode (not using debug heap)?

How I can get size of the array (100% working and stable)?

like image 361
WORLD_DYNAMIC_USER Avatar asked Nov 17 '25 20:11

WORLD_DYNAMIC_USER


1 Answers

You are relying on an implementation detail. That's how your particular implementation stores the size of the memory region where the array is placed. As you already see, the size of the memory region may be bigger than the size of the allocated array.

If you need to know the size of an array allocated with new[], you'll have to keep that value around.

like image 124
K-ballo Avatar answered Nov 19 '25 10:11

K-ballo