Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Created March 20, 2021 22:05
Show Gist options
  • Save andrewrk/a39d2acbe76152094aed781579a1f8d8 to your computer and use it in GitHub Desktop.
Save andrewrk/a39d2acbe76152094aed781579a1f8d8 to your computer and use it in GitHub Desktop.
demonstration of zig's default unit testing allocator catching various mistakes
const std = @import("std");
// leak
test "example 1" {
var array = std.ArrayList(i32).init(std.testing.allocator);
try array.append(1234);
}
// double free
test "example 2" {
const ally = std.testing.allocator;
const slice1 = try ally.alloc(i32, 10);
const slice2 = try ally.alloc(i32, 10);
ally.free(slice1);
ally.free(slice1); // oops!
}
// use after free
test "example 3" {
const ally = std.testing.allocator;
const slice1 = try ally.alloc(usize, 10);
for (slice1) |*elem, i| {
elem.* = i;
}
ally.free(slice1);
const another_array = [5]i32{ 1, 2, 3, 4, 5 };
const index = slice1[3]; // oops!
const x = another_array[index];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment