#Learning the language, issue passing an arena allocator to a function

1 messages · Page 1 of 1 (latest)

lament dune
#

I have defined a function that takes in a pointer to an allocator


fn alloc_minkowski_distance(allocator: *std.mem.Allocator, x: []const f32, y: []const f32, r: f32) ![]f64 {
    var result = std.ArrayList(f64).init(allocator);
    defer result.deinit();

    // Ensure x and y are of the same length
    if (x.len != y.len) return error.DifferentLengthVectors;

    for (x, 0..) |xi, i| {
        const diff = abs(xi - y[i]);
        const power = std.math.pow(f64, diff, r);
        try result.append(power);
    }

    return result.toOwnedSlice();
}

so when I call it:

test "alloc_minkowski_distance custom allocator test" {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit(); // Clean up all allocations when done
    comptime {
        @compileLog("Arena type: ", @TypeOf(arena));
    }
    const allocator = arena.allocator(); // This already returns a pointer

    comptime {
        @compileLog("Allocator type immediately after acquisition: ", @TypeOf(allocator));
    }

    comptime {
        @compileLog("Allocator type at compile time: ", @TypeOf(allocator));
    }

    var x: [4]f32 = .{ 0.0, 1.0, 2.0, 3.0 };
    var y: [4]f32 = .{ 4.0, 3.0, 2.0, 1.0 };
    const r: f32 = 2.0; // For example, Euclidean distance

    const result = try alloc_minkowski_distance(allocator, x[0..], y[0..], r);
    defer allocator.free(result);

    for (result) |value| {
        std.debug.print("Distance component: {}\n", .{value});
    }
}

I get the following comptime output:


Compile Log Output:
@as(*const [12:0]u8, "Arena type: "), @as(type, heap.arena_allocator.ArenaAllocator)
@as(*const [46:0]u8, "Allocator type immediately after acquisition: "), @as(type, mem.Allocator)
@as(*const [32:0]u8, "Allocator type at compile time: "), @as(type, mem.Allocator)

say we call it :

src/main.zig:162:49: error: expected type '*mem.Allocator', found 'mem.Allocator'
    const result = try alloc_minkowski_distance(allocator, x[0..], y[0..], r);
                                   

or we try by & :

src/main.zig:162:49: error: expected type '*mem.Allocator', found '*const mem.Allocator'
    const result = try alloc_minkowski_distance(&allocator, x[0..], y[0..], r);
          

Thanks in advance, still trying to get to grips with the language.

candid lance
#

dont use the pointer to an allocator

#

there isnt any point

#
fn alloc_minkowski_distance(allocator: std.mem.Allocator, x: []const f32, y: []const f32, r: f32) ![]f64 {
lament dune
#

would that not mean I create a copy of the allocator on every function call though? (it does compile if I do that, but is it correct?)

candid lance
#

it is correct

#

Allocator is a vtable and there isnt any point to taking the pointer of it

#

whether or not it will take a copy is up to the compiler