ALLOCATE
Source: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgAllocate Last revised: 2022-04-29
Allocates a block of memory from the free store.
Syntax
declare function Allocate cdecl ( byval count as uinteger ) as any ptrUsage:
result = Allocate( count )Parameters
- count — The size, in bytes, of the block of memory to allocate.
Return Value
- On success: the address of the start of the allocated memory.
- On failure (count < 0 or insufficient memory): returns the null pointer (0).
Description
Allocates count bytes from the free store (heap). The newly allocated memory is not initialized.
Warning: Allocate must not be directly used with String or UDTs containing strings, because the string descriptor is not cleared (contains random data), which may cause corruption. In those cases, use:
Callocate(clears memory to zero)New Expression(calls constructor, for UDTs)
The pointer returned is an Any Ptr pointing to the start of allocated memory. It is guaranteed to be unique, even if count is zero.
Allocated memory must be freed with Deallocate when no longer needed.
Examples
vb
' Create a buffer of 15 integers, fill with Fibonacci numbers
Const integerCount As Integer = 15
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
buffer[0] = 0
buffer[1] = 1
For i As Integer = 2 To integerCount - 1
buffer[i] = buffer[i - 1] + buffer[i - 2]
Next
For i As Integer = 0 To integerCount - 1
Print buffer[i];
Next
Deallocate(buffer)
End 0Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Memory leak example (what NOT to do):
vb
Sub BadAllocateExample()
Dim p As Byte Ptr
p = Allocate(420) ' assign pointer to new memory
p = Allocate(420) ' reassign — old address is lost and that memory is leaked
Deallocate(p)
End SubDialect Differences
- Not available in the
-lang qbdialect unless referenced with the alias__Allocate.
Differences from QB
- New to FreeBASIC.