Why does this http client code leak memory?

I have the following piece of code:

const std = @import("std");

pub fn main() !void {
    const allocator = std.heap.page_allocator;
    try _main(allocator);

fn _main(allocator: std.mem.Allocator) !void {
    var client: std.http.Client = .{ .allocator = allocator };
    defer client.deinit();

    const uri = std.Uri.parse("https://example.com") catch unreachable;
    var headers = std.http.Headers.init(allocator);
    defer headers.deinit();

    var req = try client.request(.GET, uri, headers, .{});
    try req.start();
    try req.wait();
    // var body: []u8 = try req.reader().readAllAlloc(allocator, 8192);
    // defer allocator.free(body);

    // std.log.info("status: {}", .{req.response.status});
    // std.log.info("body: {s}", .{body});

test "test" {
    const allocator = std.testing.allocator;
    try _main(allocator);

If I do zig build test I get a memory leak reported:

[gpa] (err): memory address 0x7f169582a000 leaked: 
        self.hist = try allocator.alloc(u8, size);
t (test)
            try dd.init(allocator, max_match_o
ompressor__anon_6607 (test)
    return Decompressor(@TypeOf(reader)).init(
                .inflater = try deflate.decomp
30 (test)
    return Decompress(@TypeOf(reader)).init(al
                            .gzip = std.compre
Reader()) catch return error.CompressionInitia
    try req.wait();
    try _main(allocator);
run test: error: while executing test 'test.te
Build Summary: 1/3 steps succeeded; 1 failed; 
test transitive failure
└─ run test 1/1 passed, 1 leaked
error: the following build command failed with
g-linux-x86_64-0.11.0/zig /home/jan/projects/L
ig-cache /home/jan/.cache/zig test

Why does this leak and how to fix it?

You have to deinitialize the request too:

defer req.deinit();

The fact that the request allocates memory should probably be made more explicit. The std.http section is relatively new, so it’s API hasn’t been iterated upon too much. It might feel a bit clunky right now.


Thanks, works! Update Client.zig by jw3126 · Pull Request #17254 · ziglang/zig · GitHub

1 Like