Created
March 20, 2021 22:05
-
-
Save andrewrk/a39d2acbe76152094aed781579a1f8d8 to your computer and use it in GitHub Desktop.
demonstration of zig's default unit testing allocator catching various mistakes
This file contains hidden or 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"); | |
// 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