const std = @import("std");
const expect = std.testing.expect;
const eq = std.testing.expectEqual;
test "page allocation initialized before read and freed" {
const allocator = std.heap.page_allocator;
const memory = try allocator.alloc(u8, 1024);
defer allocator.free(memory);
@memset(memory, 0);
memory[0] = 42;
try eq(@as(u8, 42), memory[0]);
try eq(@as(usize, 1024), memory.len);
}
test "debug allocator and historical GPA alias free before deinit" {
var debug = std.heap.DebugAllocator(.{}){};
{
const allocator = debug.allocator();
const memory = try allocator.alloc(u8, 512);
defer allocator.free(memory);
memory[0] = 42;
try eq(@as(u8, 42), memory[0]);
}
try expect(debug.deinit() == .ok);
var old_name = std.heap.GeneralPurposeAllocator(.{}){};
{
const allocator = old_name.allocator();
const one = try allocator.create(u32);
defer allocator.destroy(one);
one.* = 81;
try eq(@as(u32, 81), one.*);
}
try expect(old_name.deinit() == .ok);
}
test "fixed buffer capacity failure reuse and reset" {
var buffer: [1024]u8 = undefined;
var fixed = std.heap.FixedBufferAllocator.init(&buffer);
const allocator = fixed.allocator();
const memory = try allocator.alloc(u8, 256);
memory[0] = 42;
try eq(@as(u8, 42), memory[0]);
allocator.free(memory);
fixed.reset();
const all = try allocator.alloc(u8, 1024);
try eq(@as(usize, 1024), all.len);
var tiny_buffer: [8]u8 = undefined;
var tiny = std.heap.FixedBufferAllocator.init(&tiny_buffer);
const small = tiny.allocator();
try std.testing.expectError(error.OutOfMemory, small.alloc(u8, 16));
const four = try small.alloc(u8, 4);
small.free(four);
const eight = try small.alloc(u8, 8);
try eq(@as(usize, 8), eight.len);
small.free(eight);
}
fn failingAllocation(allocator: std.mem.Allocator) error{OutOfMemory,Stopped}!void {
const bytes = try allocator.alloc(u8, 32);
defer allocator.free(bytes);
bytes[0] = 9;
return error.Stopped;
}
test "testing allocator observes cleanup on error return" {
try std.testing.expectError(error.Stopped, failingAllocation(std.testing.allocator));
}
本例需在 Windows / Zig0.14.1 / Debug模式;0.15+及其它系统另验 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows / Zig0.14.1 / Debug模式;0.15+及其它系统另验
入口文件:projects/zig-lab/zig-memory-management.zig
预期结果与验证条件观察提示
- 该文件全部具名测试真实通过,未跳过或把编译成功当成执行完成。
- 具体输入、分支及数值由本章源码的expect/eq/expectError逐项核对;源码哈希与运行记录对应。
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联14章) · 含当前章节或实例 · mbskycom202611a544.zip