Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the memory size of a dynamic array?

Tags:

delphi

In Delphi, you can get the size of a value type with the sizeof() compiler magic function, but calling sizeof() on a reference type will give you the size of a pointer, not of the value it's pointing to.

For objects, you can get the memory size with the InstanceSize method, but what about for dynamic arrays? Due to padding, length(MyArray) * sizeof(element) may not be accurate. So, is there any accurate way to get the memory size of a dynamic array?

like image 762
Mason Wheeler Avatar asked Jul 11 '13 17:07

Mason Wheeler


People also ask

How do I find the size of a dynamic array?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

What is the size in memory of array?

The memory allocation for an array includes the header object of 12 bytes plus the number of elements multiplied by the size of the data type that will be stored and padding as needed for the memory block to be a multiple of 8 bytes.

What is dynamic memory array?

What is a Dynamic Array? A dynamic array is quite similar to a regular array, but its size is modifiable during program runtime. DynamArray elements occupy a contiguous block of memory. Once an array has been created, its size cannot be changed.

How are dynamic arrays stored in memory?

The elements of the dynamic array are stored contiguously at the start of the underlying array, and the remaining positions towards the end of the underlying array are reserved, or unused.


2 Answers

Between elements of a dynamic array there is no padding, Length(MyArray)*SizeOf(Element) should be accurate.

like image 114
Stijn Sanders Avatar answered Oct 17 '22 15:10

Stijn Sanders


In fact, length(MyArray) * sizeof(element) will be accurate for the array content excluding any internal dynamic array or string.

If you want the whole array used memory, including nested reference types content size, you can use our TDynArray wrapper. It is able to serialize into binary any dynamic array, including reference counted members (like dynamic arrays or strings). You have SaveTo / SaveToStream methods for this purpose, and you are able to get the actual size of all content.

Take a look at this blog article, which presents this wrapper. It is open source, and works from Delphi 5 up to XE4, in both Win32 and Win64 platform.

like image 35
Arnaud Bouchez Avatar answered Oct 17 '22 15:10

Arnaud Bouchez