fix pointer initialization

This commit is contained in:
Motiejus Jakštys 2024-10-11 09:30:17 +02:00
parent c5489bbefb
commit 519137df05
2 changed files with 12 additions and 18 deletions

View File

@ -16,10 +16,6 @@ pub fn main() !void {
try bw.flush(); // don't forget to flush! try bw.flush(); // don't forget to flush!
} }
const Tunnel = struct {
name: []u8,
};
test "simple test" { test "simple test" {
var list = std.ArrayList(i32).init(std.testing.allocator); var list = std.ArrayList(i32).init(std.testing.allocator);
defer list.deinit(); // try commenting this out and see if zig detects the memory leak! defer list.deinit(); // try commenting this out and see if zig detects the memory leak!

View File

@ -9,8 +9,7 @@ const IFF_TUN = 0x0001; // <linux/if_tun.h>
const IFF_NO_PI = 0x1000; // <linux/if_tun.h> const IFF_NO_PI = 0x1000; // <linux/if_tun.h>
const TUNSETIFF = 0x400454ca; // compile a C program, run and see const TUNSETIFF = 0x400454ca; // compile a C program, run and see
dev_buf: [posix.IFNAMESIZE:0]u8, dev: [posix.IFNAMESIZE:0]u8,
dev: [:0]u8,
tunFile: posix.fd_t, tunFile: posix.fd_t,
pub fn init(devname: ?[]const u8) !Tunnel { pub fn init(devname: ?[]const u8) !Tunnel {
@ -41,17 +40,12 @@ pub fn init(devname: ?[]const u8) !Tunnel {
} }
var tunnel = Tunnel{ var tunnel = Tunnel{
.dev = undefined, .dev = .{0} ** posix.IFNAMESIZE,
.dev_buf = .{0} ** posix.IFNAMESIZE,
.tunFile = tunFile, .tunFile = tunFile,
}; };
const ifname = mem.sliceTo(&ifr.ifrn.name, 0); const ifname = mem.sliceTo(&ifr.ifrn.name, 0);
@memcpy(tunnel.dev_buf[0..ifname.len], ifname); @memcpy(tunnel.dev[0..ifname.len], ifname);
tunnel.dev = tunnel.dev_buf[0..ifname.len :0];
std.debug.print("&tunnel = {*}\n", .{&tunnel});
std.debug.print("&tunnel.dev = {*}\n", .{tunnel.dev});
return tunnel; return tunnel;
} }
@ -61,10 +55,14 @@ pub fn close(self: *Tunnel) void {
const Tunnel = @This(); const Tunnel = @This();
test "init" { test "init with a known name" {
var tun = try init("nyotun"); var tun = try init("nyotun");
std.debug.print("&tun = {*}\n", .{&tun}); defer tun.close();
std.debug.print("&tun.dev = {*}\n", .{tun.dev}); try std.testing.expectEqualStrings("nyotun", mem.sliceTo(&tun.dev, 0));
try std.testing.expectEqualStrings("nyotun", tun.dev); }
tun.close();
test "init with no name" {
var tun = try init(null);
defer tun.close();
try std.testing.expectStringStartsWith(mem.sliceTo(&tun.dev, 0), "tun");
} }