#How can I prevent unreachable error

1 messages · Page 1 of 1 (latest)

thick bear
#

the code works as expected but i think the return number at end is causing this issue but im a bit confused.

pub fn padNumberWithZeros(number: []const u8, minLength: usize) ![]const u8 {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const length = number.len;
    
    var toReturn = number;

    if (length < minLength) {
        const paddingLength = @as(usize, @intCast(minLength - length));
        var paddedNumber: []u8 = try allocator.alloc(u8, minLength+1); 

        var index: usize = 0;
        while (index < paddingLength) : (index += 1) {
            paddedNumber[index] = '0'; 
        }

        while (index - paddingLength < length) : (index += 1) {
            paddedNumber[index] = number[index - paddingLength];
        }

        paddedNumber[index] = 0;

        toReturn = paddedNumber[0..];
    }

    return toReturn;
}
rotund rover
#

arena.deinit() invalidates everything allocated with that allocator, so the return becomes invalid before the function returns

thick bear
#

oh, so how could I prevent mem leak?

rotund rover
#

If you want to return allocated memory, you should accept an allocator: std.mem.Allocator argument so the caller knows how to free the returned memory

thick bear
#

ah gotcha, tysm!

rotund rover
#

you should also only be creating a root allocator in main

#
pub fn main() !void {
    var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    const result = try padNumberWithZeros(allocator, ...);
    defer allocator.free(result);
    use(result);
}
thick bear
#

oh 🥶 , I've been using different allocators for each file

rotund rover
#

The idea is that you know every function that might allocate because it accepts an allocator parameter, and only the caller has enough context to know what allocator the callee should be using anyway.

#

You can accept an allocator and then create an arena based on it, for example, if you want to not have to free, but you know nothing allocated with the arena will be accessible in the caller.

thick bear
#

noted! thanks a lot for this! I really appreciate it

rotund rover
#

gpa is recommended when you are learning how to use allocators since it will complain about various memory issues