#Allocation weirdness?

1 messages · Page 1 of 1 (latest)

daring schooner
#

Hey! I'm at the very beginning of my Zig learning journey, and while trying to debug a segfault, I've noticed some variables and constants seemed to be allocated ...inconsistently.

As I was debugging I've noticed addresses like 7ff7b54a9d90 and 10ab92000. I assumed the higher address (7ff...) to be part of the stack, with the lower address (10a...) being a part of the heap. To confirm my suspicions, I wrote a very minimal program to see roughly where in the address space stack-allocated variables would appear, and where in the address space heap-allocated variables would be.

To my surprise both the supposedly stack-allocated const x and the supposedly heap-allocated const z would both be addresses starting with 10ab, while a var y, which I expected to be stack-allocated, ended up at 7ff7....

Please excuse my noobishness, I have a strong feeling I'm overlooking something. I'd just love to learn what it is. Thanks!

Code

const std = @import("std");

pub fn main() !void {

    const x: usize = 0;
    std.debug.print("x = {p}\n", .{ &x });

    const arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const alloc = arena.child_allocator;

    var y: usize = 0;
    y += 1;
    std.debug.print("y = {p}\n", .{ &y });

    const z = try alloc.create(usize);
    std.debug.print("z = {p}\n", .{ z });
}

Output

x = usize@10ab2c6d8
y = usize@7ff7b54a9d90
z = usize@10ab92000

Platform info

  • MacOS
  • Zig 0.15.2
silk abyss
#

your first const, x, actually resides in static memory, not on the stack - you can read up on it in this section of the language reference.
z is allocated via the page allocator (doing arena.child_allocator just gives you back the allocator you used to initialise the arena - you probably meant to use arena.allocator(), which also means you must declare arena a var, not const) - the page allocator just decided to give you a page at the low end of the memory space

daring schooner
#

Right... static memory. Makes sense.
Yep, I did mean to use the arena.allocator() as well. I'll definitely need to take a closer look at the docs and pay more attention, lol. Thanks for the help!