A main function calls another function which returns the value of the environment variable LOGNAME
.
Printing the value shows �
The program looks like:
const std = @import("std");
pub fn getAccountName(alloc: std.mem.Allocator) ![]const u8 {
const user = std.process.getEnvVarOwned(alloc, "LOGNAME") catch |err| switch (err) {
error.EnvironmentVariableNotFound => "~",
else => return err,
};
const username = try std.fmt.allocPrint(alloc, "{s}", .{user});
defer alloc.free(username);
return username;
}
pub fn main() void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const accountName = getAccountName(allocator) catch |err| {
std.debug.print("Error: {any}\n", .{err});
return;
};
std.debug.print("Hello, {s}!\n", .{accountName});
}
and prints
Hello, �������!
instead of the value of $LOGNAME
. I think it may be something to do with allocation but can’t figure it out.