Skip to content
Pointers and Memory
step 1/5

Reading — step 1 of 5

Learn

~2 min readOOP, Pointers, File I/O

FreeBASIC has explicit pointers — like C, but with BASIC syntax. Useful for low-level work, embedded systems, and integration with C libraries.

Pointer declaration

DIM x AS INTEGER
DIM p AS INTEGER PTR

x = 42
p = @x              ' @ takes the address (like &x in C)

PRINT *p            ' 42 — dereference
*p = 100
PRINT x             ' 100 — modified through pointer

The @ operator is "address of". The * prefix is dereference. (Pascal-flavored, not C-flavored.)

NEW and DELETE

Dynamic allocation:

DIM nums AS INTEGER PTR
nums = NEW INTEGER[10]      ' allocate array of 10 ints
FOR i AS INTEGER = 0 TO 9
    nums[i] = i * 100
NEXT i
PRINT nums[5]               ' 500
DELETE [] nums              ' free

NEW Type[N] allocates an array of N. DELETE [] ptr frees an array. For single objects: NEW Type and DELETE ptr.

C-style malloc / free

Also available:

DIM buf AS UBYTE PTR
buf = ALLOCATE(1024)        ' allocate 1024 bytes
' use buf[0..1023]
DEALLOCATE(buf)

Pointer to type

TYPE Point
    x AS INTEGER
    y AS INTEGER
END TYPE

DIM p AS Point PTR = NEW Point
p->x = 3                    ' -> for member access through pointer
p->y = 4
PRINT "("; p->x; ", "; p->y; ")"
DELETE p

Linked list example

TYPE Node
    value AS INTEGER
    nxt AS Node PTR     ' "next" is a keyword — use "nxt"
END TYPE

DIM head AS Node PTR = NEW Node
head->value = 1
head->nxt = NEW Node
head->nxt->value = 2
head->nxt->nxt = 0          ' nullptr

' Walk:
DIM curr AS Node PTR = head
WHILE curr <> 0
    PRINT curr->value
    curr = curr->nxt
WEND

' Free:
curr = head
WHILE curr <> 0
    DIM next_ptr AS Node PTR = curr->nxt
    DELETE curr
    curr = next_ptr
WEND

Function pointers

Function Square(n AS INTEGER) AS INTEGER
    Return n * n
End Function

DIM fp AS Function(AS INTEGER) AS INTEGER
fp = @Square
PRINT fp(7)         ' 49

Declare a Function(types) AS retType type, then assign with @FunctionName.

When to use pointers

  • Linked data structures (lists, trees, graphs)
  • Interfacing with C libraries
  • Performance-critical buffer manipulation
  • Generic containers

Memory safety

No automatic GC in FreeBASIC. Every NEW needs a matching DELETE. Forgetting = leak. Double-free = undefined behavior.

Use DESTRUCTOR on TYPEs to clean up pointed-at memory:

TYPE List
    data AS INTEGER PTR
    DECLARE DESTRUCTOR()
END TYPE

DESTRUCTOR List()
    IF this.data <> 0 THEN DELETE [] this.data
End DESTRUCTOR

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…