Skip to content
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

Segfault when appending the the last element of an ArrayList to the ArrayList #5455

Closed
pmwhite opened this issue May 27, 2020 · 1 comment
Closed

Comments

@pmwhite
Copy link

pmwhite commented May 27, 2020

Here is the repro. It starts by adding a single element to the ArrayList and then tries to add the next to last item 100 times.

const std = @import("std");
const X = struct { x: u8 };
test "should append 100 elements to arraylist" {
    var list = std.ArrayList(X).init(std.heap.page_allocator);
    try list.append(.{ .x = 0 });
    var index: u8 = 0;
    while (index < 100) : (index += 1) {
        try list.append(list.items[list.items.len - 1]);
    }
    std.testing.expectEqual(list.items.len, 100);
}

The workaround is very simple, just explicitly copy the value before appending it. This next snippet passes the test.

const std = @import("std");
const X = struct { x: u8 };
test "should append 100 elements to arraylist" {
    var list = std.ArrayList(X).init(std.heap.page_allocator);
    try list.append(.{ .x = 0 });
    var index: u8 = 0;
    while (index < 100) : (index += 1) {
        const x = list.items[list.items.len - 1];
        try list.append(x);
    }
    std.testing.expectEqual(list.items.len, 101);
}

Another thing to note is that using u8 directly instead of the struct X doesn't trigger the segfault.

@andrewrk
Copy link
Member

andrewrk commented Oct 4, 2020

There are various open issues that cover this footgun.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants