Hi there,
I’m new to Zig (coming from Python/Go) and I am experiencing some perplexing behaviour, which I assume is based on a misunderstanding somewhere on my part. This is some code which highlights the behaviour:
fn testing(allocator: std.mem.Allocator) !void {
const m1 = try allocator.alloc(u8, 100);
defer allocator.free(m1);
std.debug.print("m1: {d}\n", .{@intFromPtr(&m1)});
const m2 = try allocator.alloc(u8, 100);
defer allocator.free(m2);
std.debug.print("m2: {d}\n", .{@intFromPtr(&m2)});
const m3 = try allocator.alloc(u8, 100);
defer allocator.free(m3);
std.debug.print("m3: {d}\n", .{@intFromPtr(&m3)});
std.debug.print("\n", .{});
for (0..5) |i| {
var memory = try allocator.alloc(u8, 100);
defer allocator.free(memory);
std.debug.print("p{d}: {d}\n", .{ i, @intFromPtr(&memory) });
}
}
test testing {
const allocator = std.testing.allocator;
try testing(allocator);
}
Outputs:
$ zig test src/main.zig
m1: 140726576320016
m2: 140726576320112
m3: 140726576320224
p0: 140726576320280
p1: 140726576320280
p2: 140726576320280
p3: 140726576320280
p4: 140726576320280
All 1 tests passed.
The first 3 lines printed, show m1, m2 and m3 all having different pointers.
The 5 last lines however all show the same pointer being used, which to me is unexpected, I would have thought I would see 5 additionally different pointers for each of the pN lines.
The actual use case which started all this, is me creating a StringHashMap, with the values being an ArrayList. The intention is to go through a set of input values which are pairs, and if the key is present in the hashmap, append to its list, otherwise create a new ArrayList with the single value in it (essentially a defaultdict(list)
in Python3 FWIW). The behaviour outlined above was causing this implementation to behave in the same way.
I have been stuck on this for days now and feel as though I have a misunderstanding at some fundamental level, or there is some behaviour within Zig that I am unaware of at play here.
Thanks very much in advance for any assistance