-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
std.fs.File.openRead() affects unrelated ArrayList #3630
Comments
Did you perhaps capture references to array list elements, and then perform an operation that changes the size, such as append() ? |
@andrewrk After clearing the array and loading the file, the code tries to read the file line by line into the ArrayList. |
The same problem appears when I remove all code modifying the array: const std = @import("std");
const Buffer = std.ArrayList(*std.ArrayList(u8));
const State = struct {
allocator: *std.mem.Allocator,
buffer: *Buffer,
const Self = @This();
fn init(alloc: *std.mem.Allocator) State {
return Self {
.allocator = alloc,
.buffer = &Buffer.init(alloc),
};
}
};
fn load(state: *State, path: []const u8) !void {
const file = try std.fs.File.openRead(path);
defer file.close();
std.debug.warn("size after file load {}\n", state.buffer.count());
if (state.buffer.count() > 0) {
var iter = state.buffer.iterator();
while (iter.next()) |line| {
line.deinit();
}
}
state.buffer.deinit();
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.direct_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var state = State.init(allocator);
std.debug.warn("siz after init {}\n", state.buffer.count());
try load(&state, "foo.txt");
std.debug.warn("size after load finished {}\n", state.buffer.count());
} Assuming the file |
Have you tried running the code in valgrind? |
Nope, not yet |
Ok, I don't have a lot of experience with But as far as I can tell, the |
All those errors from valgrind are true positives. In particular, you're returning a pointer to stack memory, which is becoming invalid upon return from the init() function. This is one of the safety issues I'm planning to address in this release cycle. This issue is a duplicate of #3180. |
Oh okay, my bad. For a moment there, I forgot the |
Loading a file with
std.fs.File.openRead()
somehow affects anArrayList
not directly related to thisFile
.I've attached two files for reproducing:
main.zig
produces correct behaviour because the file loading is done after the clearing of the array.main2.zig
doesn't exhibit correct behaviour and produces an index out out bounds error because of the wrong size (the program tries to clear an already emptyArrayList
because the size has somehow been affected).Output of
main
:Output of
main2
:main.zig:
main2.zig:
Attachments: zig.zip
The text was updated successfully, but these errors were encountered: