Hi guys, so I’m trying to write a scanner/lexer and for some reason I’m getting this issue where the allocation size does not match the free size. I’m not sure how to go about finding the cause of this. My project is here: Zrox/src at main · Dappstr/Zrox · GitHub
I’m pretty sure I’m defer
-ing every time I allocate something.
Such as here (token.zig):
pub fn to_string(self: *const Self, allocator: std.mem.Allocator) ![]const u8 {
var buffer = std.ArrayList(u8).init(allocator);
defer buffer.deinit();
try buffer.appendSlice("Token { type: ");
try buffer.appendSlice(@tagName(self.type));
try buffer.appendSlice(", lexeme: ");
try buffer.appendSlice(self.lexeme);
try buffer.appendSlice(", Literal: ");
try append_literal(&buffer, self.literal);
try buffer.appendSlice(", line: ");
try std.fmt.formatInt(self.line, 10, .lower, .{ .precision = 10 }, &buffer.writer());
try buffer.appendSlice(" }\n");
return try buffer.toOwnedSlice();
}
And here (scanner.zig):
pub fn deinit(self: *Self, allocator: std.mem.Allocator) void {
self.tokens.deinit();
keywords.deinit(allocator);
}
And here (main.zig)
fn run(source: []u8) !void {
const stdout = std.io.getStdOut().writer();
var scanner = Scanner.Scanner.init(allocator, source);
defer scanner.deinit(allocator);
var tokens = try scanner.scan_tokens();
defer tokens.deinit();
const token_slice = try tokens.toOwnedSlice();
for (token_slice) |token| {
const token_str = try token.to_string(allocator);
defer allocator.free(token_str);
try stdout.print("{s}\n", .{token_str});
}
}
fn run_file(path: []const u8) !void {
const file = try std.fs.openFileAbsolute(path, .{ .mode = .read_only });
defer file.close();
const file_size = try file.getEndPos();
const buffer: []u8 = try allocator.alloc(u8, file_size);
defer allocator.free(buffer);
const bytes_read = try file.read(buffer);
_ = bytes_read;
try run(buffer);
if (had_error) return Err_Parsing.General_Error;
}
I’m looking for some guidance to help me try and find out why my allocation and free sizes aren’t matching.