Thanks for using Compiler Explorer
Sponsors
Jakt
C++
Ada
Analysis
Android Java
Android Kotlin
Assembly
C
C3
Carbon
C++ (Circle)
CIRCT
Clean
CMake
CMakeScript
COBOL
C++ for OpenCL
MLIR
Cppx
Cppx-Blue
Cppx-Gold
Cpp2-cppfront
Crystal
C#
CUDA C++
D
Dart
Elixir
Erlang
Fortran
F#
GLSL
Go
Haskell
HLSL
Hook
Hylo
IL
ispc
Java
Julia
Kotlin
LLVM IR
LLVM MIR
Modula-2
Nim
Objective-C
Objective-C++
OCaml
OpenCL C
Pascal
Pony
Python
Racket
Ruby
Rust
Snowball
Scala
Solidity
Spice
SPIR-V
Swift
LLVM TableGen
Toit
TypeScript Native
V
Vala
Visual Basic
WASM
Zig
Javascript
GIMPLE
Ygen
zig source #1
Output
Compile to binary object
Link to binary
Execute the code
Intel asm syntax
Demangle identifiers
Verbose demangling
Filters
Unused labels
Library functions
Directives
Comments
Horizontal whitespace
Debug intrinsics
Compiler
zig 0.10.0
zig 0.11.0
zig 0.12.0
zig 0.12.1
zig 0.13.0
zig 0.2.0
zig 0.3.0
zig 0.4.0
zig 0.5.0
zig 0.6.0
zig 0.7.0
zig 0.7.1
zig 0.8.0
zig 0.9.0
zig trunk
Options
Source code
const std = @import("std"); const Blob = enum { A, B, C }; const HM = std.StringHashMap(Blob); fn wrong(alloc: anytype) !void { var hm = HM.init(alloc); defer hm.deinit(); var key: [1]u8 = .{'A'}; try hm.put(&key, .A); key[0] = 'B'; try hm.put(&key, .B); key[0] = 'C'; try hm.put(&key, .C); var keyIt = hm.keyIterator(); // note that they have all the same address here: while (keyIt.next()) |k| { std.debug.print("Key[{*}]: {s}\n", .{ k.*.ptr, k.* }); } std.debug.print("well... shit\n", .{}); } fn correct(alloc: anytype) !void { var hm = HM.init(alloc); defer hm.deinit(); // I'm using static strings here to keep things simple // depending on your use case, you'll have to figure out how to manage this: // // Store copies of the keys (hm.put(try alloc.dupe(key), ...) and free // those before de-initing HM? // // If you know keys will outlive the HM then no copies are necessary // // You could even use refcounting in particularly complex scenarios, but I'd // recommend against reaching for that unless you have to. // // there's no one correct answer here // note that if HM was managing the keys as well, we'd very often incur // completely unnecessary copies try hm.put("A", .A); try hm.put("B", .B); try hm.put("C", .C); var keyIt = hm.keyIterator(); while (keyIt.next()) |k| { std.debug.print("Key[{*}]: {s}\n", .{ k.*.ptr, k.* }); } std.debug.print("now everything looks correct again!\n", .{}); } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer { _ = gpa.deinit(); } const alloc = gpa.allocator(); try wrong(alloc); try correct(alloc); }
Become a Patron
Sponsor on GitHub
Donate via PayPal
Source on GitHub
Mailing list
Installed libraries
Wiki
Report an issue
How it works
Contact the author
CE on Mastodon
About the author
Statistics
Changelog
Version tree