Working with memory directly: allocating and freeing, copying, arenas and pools, and leak checking.
import mem
Most programs never need this package: vectors, maps and strings look after their own memory. The mem package is for low-level work, such as talking to a C library, filling a byte buffer by hand or building a data structure of your own. Its functions are thin wrappers over the C allocator (malloc, realloc, free, memcpy), plus two allocators of its own and leak counters.
•
Allocate, Reallocate and Free: one block at a time, freed by you.
•
An arena is one large block you take pieces off the front of and then release all at once; it is very fast for many small objects that share a lifetime.
•
A pool hands out and takes back blocks of one fixed size, in any order.
For a growing list of values, Vector is the safer choice; for bytes and binary formats, see encoding.binary. To watch memory from outside a function, debug has MemStats and runtime reports the machine's memory.
The things people get wrong:
•
Nothing is checked. Writing past the end of a block, freeing it twice or using it after Free, ArenaReset or PoolFree corrupts memory without an error message. salam memcheck finds these for blocks from Allocate, but not inside an arena or a pool, which are one block to it.
•
Give memory back the way it was taken: mem.Free for Allocate, the C library's own function for what a C library returns. In a -DSALAM_MEM_DEBUG build every block from Allocate has a hidden 8 byte header, so mixing the two crashes there even when a normal build seems fine.
•
Check for null. Allocate, ArenaAlloc and PoolAlloc all return it when there is no memory or no room.
•
The arena and the pool hand out memory aligned to 8 bytes, which suits every Salam type but not data that needs 16 byte alignment.
A buffer that grows
The classic use of Reallocate is a buffer that does not know its final size. Keep the length and the capacity next to the pointer, and when the buffer is full ask for twice as much. Reallocate keeps the old contents, may move them to a new address, and works on a null pointer as well, so the first growth needs no special case.
mem-guide-buffer.salam
import mem
structBuffer:
pub data: u8* = nullpub len: u64 = 0pub cap: u64 = 0endfuncappend(b &: Buffer, byte: u8):
if b.len == b.cap:
mut next := b.cap * (2asu64)
if next == (0asu64):
next = 4asu64end
b.data = mem.Reallocate(b.data asvoid*, next) asu8*
b.cap = next
println"grew to", b.cap, "bytes"end
b.data[b.len] = byte
b.len++
endfuncmain:
mut b := Buffer {}
text := "Hello, arena and pool!"repeat text.Len() in i:
append(b, text[i] asu8)
endprintln"length:", b.len, "capacity:", b.cap
mut sum := 0repeat b.len asintin i:
sum += b.data[i] asintendprintln"byte sum:", sum
mem.Free(b.data asvoid*)
end
Output
grew to 4 bytes
grew to 8 bytes
grew to 16 bytes
grew to 32 bytes
length: 22 capacity: 32
byte sum: 1941
Doubling means 22 bytes cost only four reallocations, and a million bytes about twenty. Always store the pointer that Reallocate returns: the old one may no longer be valid. For most programs a Vector<u8> does exactly this for you.
An arena per request
An arena shines when many small objects live and die together, such as everything made while handling one request or parsing one line. Allocate from the arena while you work, then call ArenaReset once at the end instead of freeing each object. The memory is reused for the next round, so the program never asks the system for more.
mem-guide-arena.salam
import mem
structToken:
pub start: int = 0pubsize: int = 0endfunctokenize(a &: mem.Arena, line: str): int:
mut count := 0mut i := 0until i < line.Len():
if line[i] == ' ':
i++
else:
t := mem.ArenaAlloc(a, size(Token)) as Token*
t[0] = Token { start = i }
until i < line.Len() and line[i] != ' ':
i++
end
t[0].size = i - t[0].start
count++
endendret count
endfuncmain:
mut arena := mem.NewArena(4096asu64)
lines := ["GET /index.html HTTP/1.1", "POST /api/orders HTTP/1.1", "DELETE /api/orders/7"]
each line in lines:
n := tokenize(arena, line)
println n, "tokens,", mem.ArenaUsed(arena), "bytes used"
mem.ArenaReset(arena)
endprintln"after the last reset:", mem.ArenaUsed(arena), "bytes used of", mem.ArenaCapacity(arena)
mem.ArenaFree(arena)
end
Output
3 tokens, 24 bytes used
3 tokens, 24 bytes used
2 tokens, 16 bytes used
after the last reset: 0 bytes used of 4096
Each allocation is rounded up to a multiple of 8 bytes, which is why one Token of two ints takes 8. ArenaAlloc returns null when the arena is full, so check the result or make the arena big enough for the largest round. After ArenaReset every pointer from the arena is stale; do not keep them across rounds.
A pool of fixed size blocks
A pool suits objects of one size that come and go in any order, such as the nodes of a list or a tree. PoolFree puts a block back on the pool's free list and the next PoolAlloc hands it out again, with no call to the system allocator either way. A pool has a fixed number of blocks; PoolAlloc returns null when they are all in use. PoolFree does not check its argument: a block freed twice goes on the free list twice and is later handed out to two owners.
mem-guide-pool.salam
import mem
importstrstructNode:
pub value: int = 0pub next: Node* = nullendfuncpush(p &: mem.Pool, head: Node*, value: int): Node*:
n := mem.PoolAlloc(p) as Node*
if n == null:
println"pool is full, dropping", value
ret head
end
n[0] = Node { value = value, next = head }
ret n
endfuncpop(p &: mem.Pool, head: Node*): Node*:
next := head[0].next
mem.PoolFree(p, head asvoid*)
ret next
endfuncmain:
mut pool := mem.NewPool(size(Node), 3asu64)
mut head := nullas Node*
repeat1to4in v:
head = push(pool, head, v * 10)
endprintln"top:", head[0].value
head = pop(pool, head)
head = push(pool, head, 99)
mut out := ""until head != null:
out = out + str.FromInt(head[0].value) + " "
head = pop(pool, head)
endprintln"stack:", out.Trim()
mem.PoolDestroy(pool)
end
Output
pool is full, dropping 40
top: 30
stack: 99 20 10
Finding leaks
Build with -DSALAM_MEM_DEBUG and Allocate and Free start counting. CheckLeaks then prints the totals to standard error and warns if any bytes are still allocated. A normal build skips the counting and costs nothing.
mem-guide-leaks.salam
import mem
funcmake_copy(text: str): u8*:
n := text.Len() asu64
p := mem.Allocate(n + (1asu64)) asu8*
repeat text.Len() in i:
p[i] = text[i] asu8end
p[text.Len()] = 0asu8ret p
endfuncmain:
a := make_copy("first")
b := make_copy("second")
mem.Free(a asvoid*)
if mem.IsMemDebug():
println"allocations:", mem.AllocCount(), "frees:", mem.FreeCount()
println"bytes still allocated:", mem.LiveBytes()
else:
println"build with -DSALAM_MEM_DEBUG to count allocations"end
mem.CheckLeaks()
mem.Free(b asvoid*)
end
Output
build with -DSALAM_MEM_DEBUG to count allocations
With the flag, the same program reports the one buffer that was still allocated when CheckLeaks ran:
The counters see memory taken through this package, and also vector storage and many string operations, but not memory a C library takes with its own malloc. For that, salam memcheck file.salam builds with AddressSanitizer and reports each leak with the place it was allocated.
funcNewPool(block_size: u64, block_count: u64): Pool
Builds a pool of block_count blocks of block_size bytes, rounded up to a multiple of 8 and at least 8. If the memory cannot be had, the pool has no blocks.
The example for this item is shown with the ones above: mem-Pool.salam
Gives a block back to the pool; the next allocation hands out the same one. It does not check that the block came from this pool or is not already free.
The example for this item is shown with the ones above: mem-Pool.salam
Changes the size of a block and keeps its contents; it may return a new address, and on a null pointer it allocates. Store the result: the old pointer may be invalid, and on failure it returns null and the old block stays yours to free.
The example for this item is shown with the ones above: mem-Allocate.salam
Flushes standard output, prints salam: out of memory and aborts. For a program that checks a null result itself and has no way to go on.
mem-Must.salam
import mem
funcmain:
a := mem.MustAllocate(8asu64) asi64*
a[0] = 7println a[0]
b := mem.MustAllocateZeroed(8asu64) asi64*
println b[0]
grown := mem.MustReallocate(a asvoid*, 64asu64)
held := mem.Allocate(16asu64)
if held == null:
mem.OutOfMemory()
end
mem.Free(held)
mem.Free(grown)
mem.Free(b asvoid*)
end
Like Allocate, but when the memory cannot be had it flushes standard output, prints salam: out of memory and aborts instead of returning null. Vector, HashMap, strings, dyn boxes and closures fail the same way.
The example for this item is shown with the ones above: mem-Must.salam
Prints the counters to standard error and warns about bytes never given back; call it at the end of the program. Without memory debugging it prints nothing, and under ASan the report comes at exit.
The example for this item is shown with the ones above: mem-Debug.salam