CodeBlanks Logo Icon CodeBlanks

Pointer

Manage C memory with Pointer<T>.

Pointer

Pointer<T> represents a C memory address in Dart. Memory is reserved with allocate and released with free. Pointer<Int32> holds an int, Pointer<Float> holds a float.

final ptr = calloc.allocate<Int32>(sizeOf<Int32>());
ptr.value = 42;
print(ptr.value);
calloc.free(ptr);

allocate and free

Memory is acquired with allocate and released with free. In modern ffi, it is allocated and freed via calloc or malloc. To avoid memory leaks, every allocate must have a matching free.

Practice Create a Pointer

In main, create a Pointer with Pointer<Int32>.fromAddress(0) and print its address value.

Starter code

main.dart
import 'dart:ffi';

void main() {
  // Int32 türünde bir Pointer oluştur, adresi 0 olsun
  // adresini yazdır
}

Sample solution

main.dart
import 'dart:ffi';

void main() {
  final ptr = Pointer<Int32>.fromAddress(0);
  print(ptr.address);
}

Expected output

0

Questions and answers

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

1 What does Pointer<T> represent?

  • An HTTP request
  • A Dart object
  • A C memory address Correct answer
  • A widget tree

Explanation: Pointer<T> wraps a C memory address in Dart; Dart object, widget and HTTP are concepts outside ffi.

2 calloc.allocate call

Question
final ptr = calloc.____<Int32>(sizeOf<Int32>());
Answer
final ptr = calloc.allocate<Int32>(sizeOf<Int32>());

Explanation: calloc.allocate allocates memory; malloc is a separate allocator object (not calloc.allocate), and get and create are not valid methods on calloc.

3 Pointer matches

Term Meaning
Pointer C memory address
allocate Memory allocation
free Memory release
calloc Zeroing allocator

All lessons in Expert