0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Zigの色々なAllocator

Posted at
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;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?