CALLOCATE
- Source: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgCallocate
- Last revised: 2021-06-16
CALLOCATE — Allocate and zero-initialize memory from the free store
Syntax
vb
declare function Callocate cdecl ( byval num_elements as uinteger, byval size as uinteger = 1 ) as any ptrUsage
vb
result = Callocate( num_elements [, size ] )Parameters
| Parameter | Description |
|---|---|
num_elements | The number of elements to allocate memory for. |
size | The size of each element in bytes. Optional; defaults to 1. |
Return Value
- On success: returns a pointer to the allocated memory block.
- On failure: returns a null pointer (
0).
Description
Callocate allocates memory from the free store for num_elements items of size bytes each, and initializes the entire block to zero.
Because the memory is zero-initialized:
- It can be used directly with
Stringvariables or UDTs containing strings, since string descriptors are initialized to zero before use. - It can be used directly with
ZStringorWStringbuffers, since the data will start as null-terminated empty strings.
For allocations that do not require zero-initialization, use Allocate instead (faster, since it skips the clearing step).
Memory allocated with Callocate must eventually be released with Deallocate. Failing to do so results in a memory leak.
Example
vb
' Allocate space for 10 integers, zero-initialized
Dim p As Integer Ptr = CAllocate(10, SizeOf(Integer))
' Fill with values
For index As Integer = 0 To 9
p[index] = (index + 1) * 10
Next
' Print values
For index As Integer = 0 To 9
Print p[index];
Next
Print
' Free the memory
Deallocate(p)Output:
10 20 30 40 50 60 70 80 90 100Dialect Differences
- Not available in the
-lang qbdialect unless referenced via its alias__Callocate.
Differences from QB
- This is a FreeBASIC extension; QB has no equivalent.
See Also
- KeyPgAllocate —
Allocate: allocate uninitialized memory - KeyPgReallocate —
Reallocate: resize an existing allocation - KeyPgDeallocate —
Deallocate: free allocated memory