#return address to stack memory, should this fail?

1 messages · Page 1 of 1 (latest)

vestal gyro
#

I'm not sure if this is recommened, or if so, why it should be fine. I'm allocating memory on the stack and returning it from the function. Is this a bad thing?

pub fn md5base64(bytes: [16]u8) []const u8 { var dest: [24]u8 = undefined; var enc = std.base64.Base64Encoder.init(std.base64.standard_alphabet_chars, '='); _ = enc.encode(&dest, &bytes); return &dest; }

supple jasper
#

Or you can just return the buffer as a value, rather than returning a pointer

vestal gyro
#

and it copies the whole thing, unlike a slice?

#

hrrmm my code is a rushed example

#

i'll update it

#

pub fn md5BytesToBase64(bytes: [16]u8) [24]u8 {
    var dest: [24]u8 = undefined;
    var enc = std.base64.Base64Encoder.init(std.base64.standard_alphabet_chars, '=');
    _ = enc.encode(&dest, &bytes);
    return dest;
}

pub fn md5BytesToHex(bytes: [16]u8) [32]u8 {
    var out: [32]u8 = undefined;
    var buf: [2]u8 = undefined;

    for (bytes, 0..16) |byte, index| {
        const hex = try std.fmt.bufPrint(&buf, "{x:0>2}", .{byte});
        const pos = index * 2;
        out[pos] = hex[0];
        out[pos+1] = hex[1];
    }
    return out;
}

fn calcMd5(file: std.fs.File) ![16]u8 {
    var md5 = std.crypto.hash.Md5.init(.{});
    var out: [16]u8 = undefined;
    var buf: [8192]u8 = undefined;
    var byte_read: u64 = 0;
    var total_bytes: u64 = 0;

    while (true) {
        byte_read = try file.read(&buf);
        total_bytes += byte_read;
        md5.update(buf[0..byte_read]);
        if (byte_read < 8192) break;
    }
    md5.final(out[0..]);
    return out;
}
#

However, I don't expect you to read all that.. but if my buggy code was annoying there is my best current effort.

May only question is, if you return an array type, does it copy the whole value? ie: [16]u8

#

or is it like a slice, with a ptr and len?

cobalt orbit
#

please highlight your code by wrapping in ```ts or rs

#

yeah arrays are values in zig so you can return them just like other values

#

in this case, i imaging a [24]u8 maybe kinda big for that but not excessive

#

*imagine

#

yes it does copy when you return an array by value

#

another option is to pass in the array by ptr: ie buf: *[24]u8

vestal gyro
#

hrrmm that's great! thank you so much for clarifying.

cobalt orbit
#

so something like this

pub fn md5BytesToBase64(bytes: [16]u8, outbuf: *[24]u8) void {
supple jasper