I am attempting to return the value of std.os.gethostname in a struct from a function, but the result is garbage. However, inside the function that gethostname is called in, the value is perfectly fine. A minimal reproducible example I have created to showcase this is here:
const std = @import("std");
const mem = std.mem;
const os = std.os;
const Hostname = struct {
hostname: []const u8,
};
fn getHostname() !Hostname {
var buffer: [os.HOST_NAME_MAX]u8 = undefined;
const hostname = try os.gethostname(&buffer);
// This works perfectly fine, and displays the hostname.
std.debug.print("{s}\n", .{hostname});
return Hostname{
.hostname = hostname,
};
}
pub fn main() !void {
const hostname = try getHostname();
// Printing the returned value in the struct has the same length but is complete garbage
std.debug.print("hostname: {s}\n", .{hostname.hostname});
}
I don't know what is going on, and am new to the language, so any help would be appreciated!