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?