Created
January 21, 2021 22:38
-
-
Save jackdbd/54e43fb2d7a97994462cd4d0a473c03e to your computer and use it in GitHub Desktop.
Memory leak example with different Zig build modes
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
//! Memory leak example with different Zig build modes. | |
//! | |
//! The program does not compile because zig detects a memory leak: | |
//! zig build-exe leak.zig -O Debug && ./leak | |
//! zig build-exe leak.zig -O ReleaseSafe && ./leak | |
//! | |
//! The program compiles, but there will be undefined behavior: | |
//! zig build-exe leak.zig -O ReleaseSmall && ./leak | |
//! zig build-exe leak.zig -O ReleaseFast && ./leak | |
//! See also: | |
//! https://ziglang.org/documentation/master/#Build-Mode | |
const std = @import("std"); | |
pub fn main() !void { | |
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; | |
defer std.debug.assert(!gpa.deinit()); | |
const allocator = &gpa.allocator; | |
const bytes = try allocator.alloc(u8, 100); | |
// memory leak because we didn't call free on the `bytes` slice | |
// Uncomment next line to free the slice, thus avoiding the memory leak | |
// defer allocator.free(bytes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment