# Allocation is not Initialization

**URL:** <https://ziggit.dev/t/allocation-is-not-initialization/3138>\
**Category:** Docs\
**Tags:** memory-management, footgun\
**Created:** [February 4, 2024, 11:16pm UTC](https://ziggit.dev/t/allocation-is-not-initialization/3138 "2024-02-04T23:16:49Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![dee0xeed](https://ziggit.dev/letter_avatar_proxy/v4/letter/d/3ab097/32.png) [@dee0xeed](https://ziggit.dev/u/dee0xeed)\
**Post date:** [February 8, 2024, 8:22pm UTC](https://ziggit.dev/t/allocation-is-not-initialization/3138/2 "2024-02-08T20:22:20Z")

</div>

> [@dude\_the\_builder](#):
>
> You can either directly set the field values after allocating the struct’s memory:

I think, it’s even better to have both `init` and `create` “constructors”, like this:

```zig
const std = @import("std");
const Allocator = std.mem.Allocator;

const User = struct {
    domain: []const u8 = "ziggit.dev",
    enabled: bool = false,

    fn init(d: []const u8, e: bool) User {
        return .{.domain = d, .enabled = e};
    }

    fn create(a: Allocator, d: []const u8, e: bool) !*User {
        var u = try a.create(User);
        u.* = init(d, e);
        return u;
    }
};

pub fn main() !void {
    const a = std.heap.c_allocator;
    const u_on_stack = User.init("dom1.org", true);
    const u_on_heap = try User.create(a, "dom2.org", true);

    std.debug.print(
        "user on stack : d = '{s}', e = {} ({*})\n",
        .{u_on_stack.domain, u_on_stack.enabled, &u_on_stack}
    );

    std.debug.print(
        "user on heap : d = '{s}', e = {} ({*})\n",
        .{u_on_heap.domain, u_on_heap.enabled, u_on_heap}
    );
}

```

Note: compile with `zig build-exe aini.zig -lc`

This way we can conveniently use either stack allocated objects or heap allocated objects, depending on whatever is needed at the moment.

Output of the program:

```plaintext
$ ./aini 
user on stack : d = 'dom1.org', e = true (aini.User@7ffc6442dff0)
user on heap : d = 'dom2.org', e = true @aini.User@4892a0)

```

---

_[View the full topic](https://ziggit.dev/t/allocation-is-not-initialization/3138)._
