Temporary Storage

Temporary Storage is linear allocator with a pointer to the start of free memory. If there is a request for memory, it advances the pointer and returns the result. If it runs out of memory, it asks the OS for more RAM. In Temporary Storage, you cannot free individual items,rather all allocated items are freed at once when reset_temporary_storage is called.

The appropriate time to call reset_temporary_storage depends from application to application. In a game loop, you could reset temporary storage at either the beginning or end of a game loop:

while true {
  input();
  simulate();
  render();
  reset_temporary_storage();
}

Here is the struct definition for Temporary Storage:

Temporary_Storage :: struct {
  data: *u8;
  size: s64;
  occupied: s64;
  high_water_mark: s64;
  overflow_allocator := __default_allocator;
  overflow_allocator_data: *void;
  overflow_pages: *Overflow_Page;
  original_data: *u8;
  original_size: s64;
}

In a debug build, if the high water mark exceeds the temporary storage memory capacity, temporary storage will default back to the default heap allocator to allocate more memory. In a release build, your program might crash, or have memory corruption problems.

New using Temporary Allocator

You can do a temporary storage allocation New using the following code:

Node :: struct {
  value: int;
  name: string;
}

node  := New(Node, allocator=__temporary_allocator);
array := NewArray(10, int, __temporary_allocator);

Resizable Array w/ Temporary Allocator

You can set the resizable array to use the temporary allocator by setting the .allocator field to __temporary_allocator.

array: [..] int;
array.allocator = __temporary_allocator;

Push Temporary Allocator

To use the Temporary Allocator as the context allocator, you can use the Push_Temporary :: () macro to push the temporary allocator to the context. When the scope closes, you get back the allocator prior.

Push_Temporary();

Using Temporary Allocator as a Stack Allocator

The temporary allocator can act as a stack allocator by using the auto_release_temp :: () macro to set the mark. Allocate whatever you want temporarily, then release all the memory at once when the stack unwinds by setting the mark back to the original location.

auto_release_temp();
1 Like