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

Memory and Resources

Most values in a tiko program live where the compiler puts them: in the frame of the procedure that declares them, created when the declaration runs and destroyed when the block ends. That is the stack, and it needs no help from you. When a value has to outlive the block that made it, or its size is known only at run time, you ask for memory on the heap, and giving it back becomes your job.

type Counter
    as int32 value
    declare constructor( byval start as int32 )
    declare destructor( )
end type

constructor Counter( byval start as int32 )
    value = start
    print "  made"; value
end constructor

destructor Counter( )
    print "  gone"; value
end destructor

function MakeOnHeap( byval n as int32 ) as Counter ptr
    dim onStack as Counter = Counter( n )   '' lives until end function
    return new Counter( n * 10 )            '' lives until delete
end function

print "calling"
dim as Counter ptr kept = MakeOnHeap( 4 )
print "back, and the heap one is still here:"; kept->value
delete kept
print "done"

Output

calling
  made 4
  made 40
  gone 4
back, and the heap one is still here: 40
  gone 40
done

MakeOnHeap makes two Counters. onStack is a local: its destructor runs at end function, which is why "gone 4" appears before the caller prints anything. The one made with new lives on the heap, so it survives the return, and the caller destroys it with delete when it has finished.

StackHeap
made bydim, var, parametersnew, allocate
destroyedat the end of its block, automaticallyby delete or deallocate
reached throughits namea pointer
a mistake looks likerarea leak, or a use after free

The pages in this section, from raw to managed:

Activities

  1. Remove the delete kept line. Which line of output disappears?
  2. Make MakeOnHeap return @onStack instead. Why is that wrong, even if it seems to work?