#Returning std.os.gethostname() value in struct results in garbage

1 messages · Page 1 of 1 (latest)

dire escarp
#

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!

stark swallow
#

gethostname writes into your buffer, since buffer is stored on the stack it and any pointers or slices of it become invalid the moment the function returns

#

your getHostname will either need to use a std.mem.Allocator to duplicate the buffer into the heap, or accept a buffer itself to write into