Slice referring to out of scope data in zig language

407 Views Asked by At

The get function below looks to me like it returns a slice referring to data in an array that will be out of scope once the function returns, and therefore is in error. Assuming this is true, is there any way to detect this at compile time or even run time in a debug mode?

I couldn't find any compiler flags that detected this error at compile time or run time and wondered if I'd missed anything that could help or this is just not something zig can detect at this time, which is fine, I'll just have to be more careful :)

This is a cut down example of a real issue I had which took some time to diagnose to demonstrate the problem

const std = @import("std");

fn get() []u8 {
    var data : [100]u8 = undefined;
    return data[0..99];
}

pub fn main() !void {
    const data = get();
    std.debug.print("Name: [{}]\n", .{data});
}
1

There are 1 best solutions below

0
On

I believe that's behaviour that's not currently frowned upon by the compiler (0.6.0 at the time of writing), based on my understanding of the Lifetime and Ownership part of the docs:

It is the Zig programmer's responsibility to ensure that a pointer is not accessed when the memory pointed to is no longer available. Note that a slice is a form of pointer, in that it references other memory.

Although it might be addressed with this issue which describes similar behaviour: https://github.com/ziglang/zig/issues/5725