Delphi - Allocating Buffers

Many commands, particularly Windows API commands, require buffers - a memory block of a specified size.

Unfortunately, there is no documentation on how to create buffers - just what you can get from the examples.

In general, after memory is allocated you are responsible for realeasing it. There are many exceptions to this, but for most "buffers", you need to explicitly release the memory. The safest way to accomplish that is to use a try..finally block.

Overview | PChar | GlobalAlloc | AllocMem | Summary


Buffers are blocks of memory. When a buffer is passed to a method, only the address of the memory block is passed, not the data in that memory. (The address to a memory block is also known as a pointer.) As a result, buffers are normally passed as constants - as parameters that can not be modified. What this means is that the address can not be modified. Even though it is passed as a constant, the buffer (the memory that the address is pointing to) can be modified ... which is frequently the point.

Most of the time you either pass the buffer (actually, its address) and its size, or you pass a buffer of a known (specified) size.

Many buffers are coded as records, arrays, or arrays of records others are just pointers to a memory block.


Most of the Windows API calls that return data in a LPCTSTR (PChar) need you to create a buffer.

This is adapted from the Delphi GetMem example

Example 2

This example (based on Changing the papersize of a print job - by Borland Developer Support Staff) creates 3 fixed size buffers. Since these buffers are created on the stack, you don't need to explicitly free the memory. In this case, data is returned via which copies one null terminated PChar string to another buffer without performing any length checking. The destination buffer must have room for at least StrLen(Source)+1 characters.

Example 3

This is a minor variation on Example 2 above.


GlobalAlloc is a Windows API function. It returns either a handle to a buffer or the address of the buffer, depending on the flag value.


AllocMem requires unit Sysutils in your uses clause.

This example is based on code in Forms.pas


These are Delphi commands - they work with pointers (memory addresses) These are Windows API calls - they work with handles When uFlags contains GMEM_MOVEABLE, use GlobalLock to convert the handle to an address. Be sure to call GlobalUnlock before calling GlobalFree.

Author: Robert Clemenzi -
URL: http:// / user / clemenzi / technical / Languages / Delphi / Buffers.html