#std.mem.sort deleting parts of array; Zig 0.11
1 messages · Page 1 of 1 (latest)
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
}```
Hmm, that's weird
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
var files = std.ArrayList([]const u8).init(allocator);
var iter = (try std.fs.cwd().openIterableDir(dir, std.fs.Dir.OpenDirOptions {
.access_sub_paths = false,
.no_follow = true,
})).iterate();
while (try iter.next()) |entry| {
try files.append(entry.name);
}
return files.toOwnedSlice();
}
you have to duplicate the names, they don't last past next
but why do some only some of them get deleted
who cares, you are accessing invalid memory, it could contain anything even old strings
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 }
calling any function at all whatsoever potentially clobbers this invalid memory in random ways
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