Skip to content

Instantly share code, notes, and snippets.

@jackdbd
Created January 21, 2021 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackdbd/54e43fb2d7a97994462cd4d0a473c03e to your computer and use it in GitHub Desktop.
Save jackdbd/54e43fb2d7a97994462cd4d0a473c03e to your computer and use it in GitHub Desktop.
Memory leak example with different Zig build modes
//! 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