const std = @import("std");
const builtin = @import("builtin");
// Global variable
// pub var allocator: std.mem.Allocator = undefined;
pub fn main() !void {
{
// General Purpose
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = general_purpose_allocator.allocator();
_ = gpa;
}
{
// Heap
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
_ = allocator;
}
{
// C allocator :: -lc or exe.linkLibC()
var arr = std.ArrayList(u8).init(std.heap.c_allocator);
try arr.append('z');
}
{
// Fixed Buffer (stack)
var buffer: [10]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buffer);
const allocator = fba.allocator();
const a = try allocator.alloc(u8, 10);
_ = a;
// const b = try allocator.alloc(u8, 1); // OOM
// _ = b;
}
{
// GPA(debug) and c_allocator(release)
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = if (builtin.mode == .Debug) gpa.allocator() else std.heap.c_allocator;
defer if (builtin.mode == .Debug) std.debug.assert(gpa.deinit() == .ok);
_ = allocator;
}
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme