Skip to content

Commit

Permalink
Explain allocation in examples/simple
Browse files Browse the repository at this point in the history
  • Loading branch information
sam701 committed Oct 13, 2024
1 parent b0b9b61 commit 7fce6a3
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions examples/simple.zig
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ fn sub3(r: *cli.AppRunner) !cli.Command {
}

fn parseArgs() cli.AppRunner.Error!cli.ExecFn {
var r = try cli.AppRunner.init(std.heap.page_allocator);
// This allocator will be used to allocate config.ip and config.arg2.
var r = try cli.AppRunner.init(allocator);

const sub2 = cli.Command{
.name = "sub2",
Expand Down Expand Up @@ -115,7 +116,25 @@ fn parseArgs() cli.AppRunner.Error!cli.ExecFn {

pub fn main() anyerror!void {
const action = try parseArgs();
return action();
const r = action();
freeConfig();
return r;
}

// Usually, you just use an arena allocator to free all allocated resources in a batch.
// This only illustrates the fact that the config data are allocated with the allocator
// you pass to cli.AppRunner.init(allocator).
fn freeConfig() void {
allocator.free(config.ip);
if (config.arg2.len > 0) {
for (config.arg2) |item| {
allocator.free(item);
}
allocator.free(config.arg2);
}
if (gpa.deinit() == .leak) {
@panic("config leaked");
}
}

fn run_sub3() !void {
Expand Down

0 comments on commit 7fce6a3

Please sign in to comment.