Skip to content

DEALLOCATE

Source: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgDeallocate Last revised: 2021-06-16

Frees previously allocated memory.

Syntax

declare sub Deallocate cdecl ( byval pointer as any ptr )

Usage:

Deallocate( pointer )

Parameters

  • pointer — The address of the previously allocated buffer.

Description

Frees memory previously allocated with Allocate. After the call, pointer becomes invalid — any further use (dereferencing or calling Deallocate again) results in undefined behavior.

Important: When memory holds a string descriptor, the string must be destroyed (set to "") before calling Deallocate, otherwise the string data cannot be freed and will cause a memory leak.

Calling Deallocate on a null pointer induces no action.

Examples

Example 1: Basic usage

vb
Sub DeallocateExample1()
    Dim As Integer Ptr integerPtr = Allocate( Len( Integer ) )

    *integerPtr = 420
    Print *integerPtr

    Deallocate( integerPtr )
    integerPtr = 0   ' Zero the pointer after deallocation
End Sub

DeallocateExample1()
End 0

Example 2: Passing pointer by reference (correct pattern)

vb
Function createInteger() As Integer Ptr
    Return Allocate( Len( Integer ) )
End Function

Sub destroyInteger( ByRef someIntegerPtr As Integer Ptr )
    Deallocate( someIntegerPtr )
    someIntegerPtr = 0   ' Null the original pointer
End Sub

Sub DeallocateExample3()
    Dim As Integer Ptr integerPtr = createInteger()
    *integerPtr = 420
    Print *integerPtr
    destroyInteger( integerPtr )
    Assert( integerPtr = 0 )
End Sub

DeallocateExample3()
End 0

Dialect Differences

  • Not available in the -lang qb dialect unless referenced with the alias __Deallocate.

Differences from QB

  • New to FreeBASIC.

See Also

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