When and how is memory released by library calls such as std.fmt.allocPrint

Hello,

As a newbie I am going over this excellent tutorial wherein we see examples of how memory is allocated by library functions, but I fail to see were a defer is used to deallocate the memory. I have coded this and used this to check for leaks:

    const leaked1 = gpa.detectLeaks();
    std.debug.print("leak 1 = {}\n", .{leaked1});

No leaks show up, so were and how is memory deallocated? At the end I show 3 such examples I have used.

TIA for the help.

Example 1:

    {
        const say = std.fmt.allocPrint(allocator, "It's over {d}!!!", .{user.power});
        // defer allocator.free(say);
        // std.debug.print("Heap allocated string = {s}\n", .{say.*});
        if (say) |v| {
            std.debug.print("Heap allocated string = {s}\n", .{v});
            defer allocator.free(v);
        } else |err| {
            std.debug.print("if error = {}\n", .{err});
        }
    }

Example 2:

    const leto_name = "Leto";
    {
        var name_buf: [100]u8 = undefined;
        const greeting = try std.fmt.bufPrint(&name_buf, "Hello {s}", .{leto_name});

        std.debug.print("{s}\n", .{greeting});
    }

Example 3:

    {
        const out = std.io.getStdOut();

        try std.json.stringify(.{
            .this_is = "an anonymous struct",
            .above = true,
            .last_param = "are options",
        }, .{ .whitespace = .indent_2 }, out.writer());
    }

In example 1, you can se the call to free. The defer there is redundant.
In example 2, the memory comes from name_buf, which is stack allocated, so you should not free it.
In example 3, the data is being formatted and printed straight into the console, so no allocation is necessary.

5 Likes

@LucasSantos91 Thanks for the reply.