Revision [13153]

This is an old revision of KeyPgAllocate made by JeffMarshall on 2008-04-24 15:43:04.



Allocates a block of memory from the free store

result = Allocate( size )

The size, in bytes, of the block of memory to allocate.

Return Value:
If successful, the address of the start of the allocated memory is returned. Otherwise, if the requested block size could not be allocated, or if count < 0, then the null pointer (0) is returned.

Attempts to allocate, or reserve, count number of bytes from the free store (heap). The initial value of newly allocated memory is unspecified. The pointer that is returned is an KeyPgAny any KeyPgPtr ptr and points to the start of the allocated memory. This pointer is guaranteed to be unique, even if count is zero.
Allocated memory must be deallocated, or returned back to the free store, with KeyPgDeallocate Deallocate when no longer needed.

'' This program uses the ALLOCATE(...) function to create a buffer of 15 integers that is
'' then filled with the first 15 numbers of the Fibonacci Sequence, then output to the
'' screen. Note the call to DEALLOCATE(...) at the end of the program.

    Const integerCount As Integer = 15

    '' Try allocating memory for a number of integers.
    Dim buffer As Integer Ptr
    buffer = Allocate(integerCount * SizeOf(Integer))

    If (0 = buffer) Then
        Print "Error: unable to allocate memory, quitting."
        End -1
    End If

    '' Prime and fill the memory with the fibonacci sequence.
    buffer[0] = 0
    buffer[1] = 1
    For i As Integer = 2 To integerCount - 1
        buffer[i] = buffer[i - 1] + buffer[i - 2]

    '' Display the sequence.
    For i As Integer = 0 To integerCount - 1
        Print buffer[i] ;

    End 0
Output is:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377


It is important to free allocated memory if it's not going to be used anymore. Unused memory that isn't freed is simply wasting memory, and if the address of that memory is somehow overwritten or forgotten, that memory can never be freed (this condition is known as a memory leak, and should be avoided at all costs). The following example demonstrates a function with a memory leak, where the address of allocated memory is lost, never to be freed (if this function is called frequently, the memory that is wasted can add up quickly).

Sub AllocateExample2()
   Dim p As Byte Ptr = 0

   p = Allocate(420)               '' assign pointer to new memory

   p = Allocate(420)               '' reassign pointer to different memory,
                                   '' old address is lost and that memory is leaked
End Sub

   End 0

Platform Differences:
  • This procedure is not guaranteed to be thread-safe.

Dialect Differences:
Differences from QB:
See also:
Back to Memory Functions
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki phatcode