I've the below code for reading and printing the content of the specified file, this code is working fine:
const std = @import("std");
pub fn main() !void {
const contents = try readFile("index.html");
std.debug.print("File contents: {s}\n", .{contents});
}
pub fn readFile(filename: []const u8) ![]u8 {
const allocator = std.heap.page_allocator;
const file = try std.fs.cwd().openFile(filename, .{});
defer file.close();
const contents = try file.reader().readAllAlloc(allocator, std.math.maxInt(usize));
// defer allocator.free(contents);
return contents;
}
I was wondering why it gave me an error once I tried to clear the memory using defer allocator.free(contents);
and worked fine once I removed it, do not I need to free the memory allocation?
defer
works on the block level. allocator.free(contents)
is called before readFile
returns, which means the function tries to return and free the memory at the same time. This is simply wrong.
Modify readFile
to accept an allocator instead and free the memory outside of the function. For example:
pub fn main() !void {
const allocator = std.heap.page_allocator;
const contents = try readFile(allocator, "index.html");
defer allocator.free(contents);
std.debug.print("File contents: {s}\n", .{ contents });
}
pub fn readFile(allocator: std.mem.Allocator, filename: []const u8) ![]u8 {
const file = try std.fs.cwd().openFile(filename, .{});
defer file.close();
const contents = try file.reader().readAllAlloc(allocator, std.math.maxInt(usize));
return contents;
}