#how to free a pointer which may or may not be heap allocated

1 messages · Page 1 of 1 (latest)

drowsy parcel
#

I've got code that looks like this:

    if (parsed_args.args.mapfile) |mapfile| {
        input.map_file = mapfile;
    } else {
        // option B: find the map in tfpath based on the name in the demo header
        input.map_file = try get_map_absolute_path(allocator, &input, &parsed_args, &params);
    }
    defer allocator.free(input.map_file.?);

If I dont have mapfile in args, then input.map_file is a heap-allocated pointer, and everything works fine. If I supply mapfile to the program, it panics with invalid free. If I put the defer in the conditional then it will get removed right away. Whats the Zig Way to do this?

gritty dock
#

unsure if there's a better way, but I usually just go with the simplest/dumbest thing:

    var map_file_needs_free: bool = false;
    if (parsed_args.args.mapfile) |mapfile| {
        input.map_file = mapfile;
    } else {
        // option B: find the map in tfpath based on the name in the demo header
        input.map_file = try get_map_absolute_path(allocator, &input, &parsed_args, &params);
        map_file_needs_free = true;
    }
    defer if (map_file_needs_free) allocator.free(input.map_file.?);
shut plaza
#

man I love those optionals

old magnet
#

just to point out this could be tidied a bit:

const map_file_needs_free: bool = parsed_args.args.mapfile == null;
input.map_file = parsed_args.args.mapfile orelse
    try get_map_absolute_map(allocator, &input, &parsed_args, &params);
defer if (map_file_needs_free) allocator.free(input.map_file.?);
drowsy parcel
#

what markdown syntax highlighting specifier are you guys using lol

rocky ravine
#

ts and rs work pretty well

drowsy parcel
#

aight