CodeBlanks Logo Icon CodeBlanks

Pointer

Learn memory management with Pointer.

Pointer

Pointer is the dart:ffi type that represents C-side memory addresses. Pointer<Int32> represents an integer address, Pointer<Double> a floating-point address, and Pointer<Void> an untyped address.

Pointers are read/written via the value property: ptr.value = 42; or ptr.value. To allocate memory, use calloc<Int32>() or malloc<Int32>(). Pointers are not managed by Dart's garbage collector; manual deallocation is required.

Memory management

Pointer memory is not managed by Dart's garbage collector; manual management is required. calloc allocates zeroed memory, malloc unzeroed. Allocated memory is freed with ptr.callocFree() or ptr.free().

Incorrect management causes leaks or double frees. The using or arena patterns automatically free memory. Pointer arithmetic is done with ptr + 1 or ptr.elementAt(n).

Practice A PointerInfo class

Define a PointerInfo class with final String type; final int address; PointerInfo(this.type, this.address); field and constructor. Add a String describe() => 'Pointer<$type> @ $address'; method. In main create final pi = PointerInfo('Int32', 0);; print with print(pi.describe());.

Starter code

main.dart
void main() {
  // define a PointerInfo class (type, address; describe)
  // create a PointerInfo; print describe()
}

Sample solution

main.dart
class PointerInfo {
  final String type;
  final int address;
  PointerInfo(this.type, this.address);
  String describe() => 'Pointer<$type> @ $address';
}

void main() {
  final pi = PointerInfo('Int32', 0);
  print(pi.describe());
}

Expected output

Pointer<Int32> @ 0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 A Pointer type

Question
final ptr = Pointer<____>.fromAddress(0);
Answer
final ptr = Pointer<Int32>.fromAddress(0);

Explanation: Pointer<Int32> is an integer memory address.

2 Match the Pointer operations

Term Meaning
Pointer<Int32> Integer address
ptr.value Read/write value
calloc<T>() Zeroed allocation
ptr.free() Deallocation

3 What manages pointer memory?

  • Dart garbage collector
  • Manual management Correct answer
  • Automatically by browser
  • By the OS automatically

Explanation: pointer memory is managed manually (calloc/malloc + free).

All lessons in Expert