Skip to content

Commit b9318ec

Browse files
memory: use a GPA in Debug mode and an Arena (page based) on Release
Signed-off-by: Francis Bouvier <[email protected]>
1 parent 57918e9 commit b9318ec

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

src/main.zig

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -158,12 +158,31 @@ fn printUsageExit(execname: []const u8, res: u8) void {
158158
pub fn main() !void {
159159

160160
// allocator
161-
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
162-
defer arena.deinit();
163-
const alloc = arena.allocator();
161+
// - in Debug mode we use the General Purpose Allocator to detect memory leaks
162+
// - in Release mode we use an Arena Allocator based on the page allocator
163+
var alloc: std.mem.Allocator = undefined;
164+
var gpa: ?std.heap.GeneralPurposeAllocator(.{}) = null;
165+
var arena: ?std.heap.ArenaAllocator = null;
166+
if (builtin.mode == .Debug) {
167+
gpa = std.heap.GeneralPurposeAllocator(.{}){};
168+
alloc = gpa.?.allocator();
169+
} else {
170+
arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
171+
alloc = arena.?.allocator();
172+
}
173+
defer {
174+
if (gpa) |*_gpa| {
175+
switch (_gpa.deinit()) {
176+
.ok => std.debug.print("No memory leaks\n", .{}),
177+
.leak => @panic("Memory leak"),
178+
}
179+
} else if (arena) |*_arena| {
180+
_arena.deinit();
181+
}
182+
}
164183

165184
// args
166-
var args = try std.process.argsWithAllocator(arena.allocator());
185+
var args = try std.process.argsWithAllocator(alloc);
167186
defer args.deinit();
168187

169188
const execname = args.next().?;
@@ -263,7 +282,7 @@ pub fn main() !void {
263282
std.log.info("Listening on: {s}:{d}...", .{ host, port });
264283

265284
// loop
266-
var loop = try jsruntime.Loop.init(arena.allocator());
285+
var loop = try jsruntime.Loop.init(alloc);
267286
defer loop.deinit();
268287

269288
// listen
@@ -279,7 +298,7 @@ pub fn main() !void {
279298
const vm = jsruntime.VM.init();
280299
defer vm.deinit();
281300

282-
var loop = try jsruntime.Loop.init(arena.allocator());
301+
var loop = try jsruntime.Loop.init(alloc);
283302
defer loop.deinit();
284303

285304
var browser = Browser{};

0 commit comments

Comments
 (0)