Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

nullptr

nullptr is the null pointer: an address of nothing. It converts to every pointer type, and it is how a pointer says "there is no value here", such as the end of a linked list.

'' nullptr is the null pointer: an address of nothing.
type Node
    as int32 value
    as Node ptr nextNode                '' nullptr marks the end
end type

dim as Node nodeC = ( 3, nullptr )
dim as Node nodeB = ( 2, @nodeC )
dim as Node nodeA = ( 1, @nodeB )

print "the list:";
dim as Node ptr at = @nodeA
do while at <> nullptr                  '' test before you follow
    print at->value;
    at = at->nextNode
loop
print

'' 0 is also null, but it is an integer to everything that has to
'' choose a type. nullptr is a pointer.
sub Show overload ( byval n as integer )
    print "  Show( integer )"
end sub

sub Show overload ( byval p as any ptr )
    print "  Show( any ptr )"
end sub

print "Show( 0 ) and Show( nullptr ):"
Show( 0 )
Show( nullptr )

var a = 0                               '' an integer
var b = nullptr                         '' a pointer
print "var from 0, then from nullptr:"
Show( a )
Show( b )

Output

the list: 1 2 3
Show( 0 ) and Show( nullptr ):
  Show( integer )
  Show( any ptr )
var from 0, then from nullptr:
  Show( integer )
  Show( any ptr )

The list's last node holds nullptr in nextNode, and the loop tests for it before following the link. That test is the whole discipline of null pointers: test a pointer that may be null before you follow it.

0 works as a null pointer too, but 0 is an integer, and wherever the compiler has to choose a type, it chooses an integer's. Given an integer overload and an any ptr one, Show( 0 ) picks the integer and Show( nullptr ) the pointer, and var copies the same choice. Write nullptr whenever you mean a pointer.

Following a null pointer is a bug, and under -exx the program stops at the access instead of crashing somewhere further on:

#cmdline "-exx"

type Point
    as int32 x, y
end type

'' -exx checks every access through a pointer for null.
dim as Point ptr p = nullptr
print p->x                              '' stops here
print "not reached"

Aborting due to runtime error 7 (null pointer access) at line 9 of nullcheck.tiko::()

The check covers *p, p->x and p[i]. The program ends with runtime error 7, and 7 is its exit status. Without -exx the same program crashes with an access violation. Runtime errors in general are covered in Runtime errors.

Activities

  1. Add a fourth node to the front of the list.
  2. In nullcheck.tiko, replace p->x with *cptr( int32 ptr, p ). Does the check still catch it?