Created
August 30, 2021 04:14
-
-
Save coderlyfe/1d50e351d27102ba1ff010adf2d94e16 to your computer and use it in GitHub Desktop.
zig memory allocators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
pub fn main() !void { | |
// fixe buffer allocator | |
var buffer: [1000]u8 = undefined; | |
const allocator = &std.heap.FixedBufferAllocator.init(&buffer).allocator; | |
const memory = try allocator.alloc(u8, 5); | |
defer allocator.free(memory); | |
memory[0] = 'b'; | |
memory[1] = 'o'; | |
memory[2] = 'b'; | |
std.debug.print("{s} \n", .{memory}); | |
std.mem.copy(u8,memory, "hello"); | |
std.debug.print("{s} \n", .{memory}); | |
const w = std.mem.concat(allocator, u8, &[_][]const u8{ "bobby ", "bouche" }); | |
std.debug.print("{s} \n", .{w}); | |
// general purpose allocator | |
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; | |
const allocator1 = &gpa.allocator; | |
const bytes = try allocator1.alloc(u8, 1); | |
defer allocator1.free(bytes); | |
bytes[0] = 'L'; | |
std.debug.print("{s} \n", .{bytes}); | |
// heap allocator must use | |
const allocator2 = std.heap.page_allocator; | |
const bytes1 = try allocator2.alloc(u8, 25); | |
defer allocator2.free(bytes1); | |
std.mem.copy(u8, bytes1, "zig is awesome"); | |
std.debug.print("{s} \n", .{bytes1}); | |
// c heap allocator must use -lc switch | |
const allocator3 = std.heap.c_allocator; | |
const bytes3 = try allocator3.alloc(u8, 25); | |
defer allocator3.free(bytes3); | |
std.mem.copy(u8, bytes3, "zig is great"); | |
std.debug.print("{s} \n", .{bytes3}); | |
// arena allocator | |
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); | |
defer arena.deinit(); | |
var allocator4 = &arena.allocator; | |
const m1 = try allocator4.alloc(u8, 1); | |
std.mem.copy(u8, m1, "I"); | |
const m2 = try allocator4.alloc(u8, 4); | |
std.mem.copy(u8, m2, "LOVE"); | |
const m3 = try allocator4.alloc(u8, 3); | |
std.mem.copy(u8, m3, "ZIG"); | |
std.debug.print("{s} {s} {s}\n", .{m1, m2, m3}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment