Making Manual Memory Management More Manageable
Heads up!
This article is the second part of a series where I think out loud and share the different considerations I’ve been making when picking a memory model for Conjure.
Conjure originally started as an attempt to create a friendlier C, with modern and opinionated syntax, a real toolchain, and a standard library that doesn’t fight you. So sticking with manual memory management only made sense. It’s the approach taken by other modern languages like Zig and Odin1, and it’s arguably what made C the staple it still is.
That’s not to say we can’t make managing memory yourself a nicer experience. I explored (and prototyped!) a handful of ideas to see how they’d actually feel in practice. This post walks through the common pain points and what I landed on for each.
#What is manual memory management?
I mean… it’s in the name. You’re in charge of explicitly asking the operating system for memory and giving it back. For every alloc() there’s a matching free(). The compiler does nothing automatic, and every pointer and its lifespan is your problem.
That said, “manual” doesn’t mean the compiler sits on its hands. In Conjure, alloc and free are compiler intrinsics rather than plain library calls, so the compiler is free to elide a heap allocation entirely when escape analysis proves the value never outlives its scope. You write the obvious alloc, and if it turns out to be just a local, it never touches the heap.
Debug builds go further with runtime checks and memory tracing to help catch leaks and use-after-free while you’re developing. Those get stripped from release builds, so you pay nothing for them in production.
With that out of the way, let’s talk about the common pain points and what I explored to soften each one.
#Forgetting to clean up
One of the easier (and proven) wins is the defer keyword. It schedules cleanup at scope exit so it doesn’t get lost across early returns2. The nice part is it isn’t limited to freeing pointers. You can defer closing file handles, releasing locks, or tearing down sockets.
func example() {
var players = alloc(sizeof(Monster) * 16)
defer free(players)
// ...
}
Types can also declare their own cleanup with an overload free hook3, so freeing a Player cascades into its name and weapon without the caller knowing the details. You still trigger it yourself with free()4, but the teardown logic lives with the type instead of getting copy-pasted at every call site.
overload free(p &Player) {
free(p.name)
if w = p.weapon { free(w) }
}
#Fighting back against “use after free” bugs
There’s no compile-time solution for use-after-free in a manual model, at least not without dragging in the Rust-style ownership machinery I was trying to avoid. What Conjure can do is make the failure loud instead of silent.
In debug builds, freed pointers get poisoned. Instead of leaving the memory looking valid, free() scribbles a known-bad pattern over it, so reaching through a dangling pointer trips immediately during development rather than corrupting something three frames later. Like the other debug checks, this disappears in release builds.
The other angle is enforcing ownership through the pointer types themselves. Conjure splits pointers into *T (owned) and &T (borrowed), and attaches rules to each. A &T refers to something you don’t own, so it can’t be handed to free(). Only a *T, which represents a real heap allocation, can.
func inspect(p &Player) {
free(p) // compile error: &T is borrowed, not owned
}
Borrowed pointers also aren’t allowed to escape the scope that created them5, which shuts down a whole class of dangling references. You can push this further by having a reference to a stack value produce a &T instead of a *T. Since &T can’t escape and can’t be freed, a pointer into stack memory physically can’t leak out of the function that owns that stack. It’s the same distinction pulling double duty: telling you who owns what, and quietly closing off the easiest ways to create a dangling pointer.
#Nullable pointers
There’s one more rule riding along with the pointer/reference types. By default a *T or &T always points at something real. The compiler won’t let you assign null to one or leave it uninitialized. If you want the option of nothing, you opt into it with a ? prefix: ?*T for a nullable owned pointer, ?&T for a nullable borrow.
struct Player {
weapon ?*Weapon // might be unarmed
}
A plain *Weapon would say every player is always holding a weapon. By using ?*Weapon, our Player can be “unarmed”. The tradeoff is that you can’t just follow it. Before you touch a nullable pointer, you have to account for the null case first.
All Conjure needs to ensure this is an assertion with a conditional.
print(p.weapon.name) // error: `p.weapon` may be `null`
if p.weapon {
print(p.weapon.name)
}
This still comes with the risk that another thread/routine could set it to null. One possible solution is to allow sugar where we assert and assign it to a new value whose type would be *Weapon instead of ?*Weapon. Because Conjure treats assignments as statements and not expressions, we could unambiguously handle this at the parser level like so:
if w = p.weapon {
// w is a *Weapon here, guaranteed non-null
free(w)
}
The payoff is that a null dereference stops being a runtime surprise. You can’t accidentally chase a ?*T without checking it, so the compiler catches the mistake up front, the same way it stops you freeing a borrow.
#Complex data types (slices, lists, strings)
Aggregates bring their own cleanup headaches. A dynamic array owns a backing buffer that has to grow and eventually be freed, while a slice is just a view into someone else’s buffer and must never free it. Get that wrong and you’ve got either a leak or a double-free.
Strings are the worst offender, so much so that they got their own post. The short version is that a string carries a tag for how it was created, so string literals and borrowed substrings quietly skip the free path. You can hand any string to free() and the right thing happens, without special-casing your cleanup around where the string came from.
#Where that leaves manual management
None of this turns manual memory management into something it isn’t. You’re still the one holding the pointers. What these changes buy is a set of guardrails that catch the common mistakes early and keep the cleanup code honest, without giving up the things that made manual management appealing in the first place.
- Predictable: every allocation and free is visible in source.
- Zero runtime overhead in release builds beyond the allocator itself.
- Maps directly to C, so the FFI story is essentially free.
-
deferandoverload freekeep cleanup close to the code that owns it. - Debug builds poison freed memory and trace allocations to catch leaks and use-after-free during development.
-
*Tvs&Tencodes ownership in the type system, stopping borrows from being freed or escaping their scope. - No compile-time guarantee against use-after-free; the safety net is debug-only.
- Forgetting a
free()still leaks in release builds. - Cascading ownership has to be spelled out in
overload free. - You’re still the one reasoning about lifetimes across function boundaries and stored pointers.
- Added complexity from another pointer type with its own rules.
I have a soft spot for this model. It’s zero-overhead, it maps straight onto C, and it stays out of the way of arenas, which is a pattern that is near and dear to me. When you free an entire arena in one shot, per-object free() calls are the wrong abstraction anyway, so most of the manual burden disappears in the style I actually want to write.
What still worries me is the silent failure mode. Once you’re in a release build, a use-after-free is undefined behavior with no seatbelt. I’d reach for this in a hot path without hesitation, but I’m less comfortable handing it to someone coming from C# as their only tool.
#Going further: move semantics
Everything above keeps you in charge and just hands you better tools. If you’re willing to give up a little of that control, the compiler can start catching ownership mistakes for you at compile time.
Move semantics is the next step up. Every owning binding is either Live or Moved. Assigning it, passing it by value, returning it, or storing it in a struct transfers ownership: the source becomes Moved, and any use after that is a compile error. Only the current owner ever cleans up, so double-frees stop existing. It’s essentially the Rust model with the borrow checker taken out, tracked by a simple local pass with no lifetime annotations.
Therein lies the problem though… we’re starting to add more ceremony and yet we’re not gaining the absolute safety guarantees that Rust provides. So both the manual tools and move semantics still ask you to reason about ownership yourself, by hand in one case and through the type system in the other.