Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate a byte array and free it afterwards in delphi

I would like to allocate space (dynamic size) with a byte array and get a pointer to the "spacearea" and free it later if I don't need it anymore.

I know about VirtualAlloc, VirutalAllocEx and LocalAlloc. Which one is the best and how can I free the memory afterwards?

Thank you for your help.

like image 788
Ben Avatar asked Aug 03 '12 12:08

Ben


2 Answers

I don't think it is a good idea to use the winapi for that instead of the native Pascal functions.

You can simply define an array of bytes as

var yourarray: array of byte;

then it can be allocated by

setlength(yourarray, yoursize);

and freed by

setlength(yourarray, 0);

Such an array is reference counted and you can access individual bytes as yourarray[byteid]

Or if you really want pointers, you can use:

var p: pointer;

GetMem(p, yoursize);

FreeMem(p);
like image 80
BeniBela Avatar answered Sep 27 '22 17:09

BeniBela


You should better use GetMem/FreeMem or a dynamic array, or a RawByteString. Note that GetMem/FreeMem, dynamic arrays or RawByteString uses the heap, not the stack for its allocation.

There is no interest about using VirtualAlloc/VirtualFree instead of GetMem/FreeMem. For big blocks, the memory manager (which implements the heap) will call VirtualAlloc/VirtualFree APIs, but for smaller blocks, it will be more optimized to rely on the heap.

Since VirtualAlloc/VirtualFree is local to the current process, the only interest to use it is if you want to create some memory block able to execute code, e.g. for creating some stubbing wrappers of classes or interfaces, via their VirtualAllocEx/VirtualFreeEx APIs (but I doubt it is your need).

If you want to use some memory global to all processes/programs, you have GlobalAlloc/GlobalFree API calls at hand.

like image 30
Arnaud Bouchez Avatar answered Sep 27 '22 17:09

Arnaud Bouchez