#std.mem.sort deleting parts of array; Zig 0.11

1 messages · Page 1 of 1 (latest)

lusty mica
#

Can you share your code?

desert lotus
#
fn cmp(_: void, a: []const u8, b: []const u8) bool {
    return std.mem.order(u8, a, b) == .lt;
} 

pub fn main() !void {
    var files: [][]const u8 = undefined;

    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();

    var allocator = arena.allocator();
    files = try get_files(allocator, dir);        
    defer allocator.free(files);

    std.debug.print("{s}\n", .{files}); // All there

    std.mem.sort([]const u8, files, {}, cmp);

    std.debug.print("{s}\n", .{files}); // Some randomly removed
}```
lusty mica
#

Hmm, that's weird

fierce tulip
#

What does get_files look like? I can't come up with any other problem than that it allocates the array on the stack

#

Although it also feels unlikely since you pass an allocator to it

desert lotus
wind ether
#

you have to duplicate the names, they don't last past next

desert lotus
#

but why do some only some of them get deleted

wind ether
#

who cares, you are accessing invalid memory, it could contain anything even old strings

desert lotus
#

but when I print it out the first time they're all there. then they only disappear when I call sort

#
{ .local, .dbus, .vimrc, .w3m, .cache, .cargo, .xinitrc, .Xauthority, .zshrc, .surf, .inputrc, code, .vim, .config, .lesshst, .ssh }

{ �, .inputrc, hst, .ssh, .surf,
                                 , , , , , .Xauthority, .cache, .cargo, .vimrc, .w3m, .xini }
wind ether
#

calling any function at all whatsoever potentially clobbers this invalid memory in random ways

fierce tulip
#

The stack is not actually destroyed when you leave a scope, it's just not preserved and can be overwritten by future operations

#

So the names that you have on the stack are not overwritten by the print function, probably because it's considerably smaller stack-wise than your get_files