0

I am trying to make a sort of input() function for a project I've been working on.

The function simply reads from stdin and returns the string.

Here's what I came up with:

const std = @import("std");

pub fn input_expression() ![]u8 {
    const stdin = std.io.getStdIn().reader(); 
    var buf: [32]u8 = undefined;

    const result = stdin.readUntilDelimiterOrEof(buf[0..], '\n') catch |err| {
        return err;
    };

    if (result == null) {
        return error.NoData;
    }
    std.debug.print("result: {s}\n", .{result.?});
    return result.?;
}

This is placed inside an external module called interface.zig.

Inside of main, I import interface.zig:

const std = @import("std");
const interface = @import("interface.zig");

pub fn main() !void {
    const expr: []u8 = try interface.input_expression();
    std.debug.print("expr: {s}\n", .{expr});
}

I would expect the output from 'inside' the function (meaning the std.debug.print(result: {}) inside of it) to be the same as the output of main.

Instead here is the output

205 + 2 (Input)
result: 205 + 2
expr: ��#8�

1 Answer 1

4

What you read from stdin is being stored on the stack, in the stack frame of the function input_expression . Once the function returns it's stack frame and thus the variable buf are no longer valid. Their values are undefined. When you print your result you are referencing "old stack memory". An that's what you can see in the output.

You either have to pass a buffer as a variable to your function that has a longer lifetime or heap allocate the result and free it later.

If you are new to lower level programming languages maybe have a look at this too: What's the difference between Stack Memory and Heap Memory?

Sign up to request clarification or add additional context in comments.

2 Comments

Can I ask one quick clarification (I dont know if this should be its own question, sorry) why doesn't zig warn me that I tried printing an undefined variable? Why does it just print rubbish?
The print function just takes a slice (i.e. a range of data) and prints whatever is there. It shouldn't care what we give it. Once we call print, there is no physical state that we could check if the data pointed to is well defined or not, it's just memory. If at all, the compiler might warn us that the function input_expression() returns a struct with a pointer to a local stack variable. But these kinds of things might be hard to track in all cases. I haven't written a compiler to be fair so I might be wrong. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.