Skip to content

CALLOCATE


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 ptr

Usage

vb
result = Callocate( num_elements [, size ] )

Parameters

ParameterDescription
num_elementsThe number of elements to allocate memory for.
sizeThe 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 String variables or UDTs containing strings, since string descriptors are initialized to zero before use.
  • It can be used directly with ZString or WString buffers, 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 100

Dialect Differences

  • Not available in the -lang qb dialect unless referenced via its alias __Callocate.

Differences from QB

  • This is a FreeBASIC extension; QB has no equivalent.

See Also

Translated from FreeBASIC official docs. Contact us for removal if infringed.
FreeBASIC is an open-source project, not affiliated with Microsoft