Skip to content

ArrayList segfault when appending large value #19215

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

Closed
nohenry opened this issue Mar 7, 2024 · 1 comment
Closed

ArrayList segfault when appending large value #19215

nohenry opened this issue Mar 7, 2024 · 1 comment
Labels
bug Observed behavior contradicts documented or intended behavior

Comments

@nohenry
Copy link
Contributor

nohenry commented Mar 7, 2024

Zig Version

0.12.0-dev.3158+1e67f5021

Steps to Reproduce and Observed Behavior

Reproducible example:

const std = @import("std");

pub const Large = struct {
    a: u64 = 0,
    b: u64 = 1,
};

pub fn main() !void {
    var alloc = std.heap.GeneralPurposeAllocator(.{}){};

    var nodes = std.ArrayList(Large).init(alloc.allocator());
    try nodes.ensureTotalCapacityPrecise(5);
    try nodes.appendSlice(&.{ .{}, .{}, .{}, .{}, .{} });

    try nodes.append(nodes.items[2]);
}

Compiling with default optimizations:

$ zig build run

Segmentation fault at address 0x7061d50c7020
/usr/lib/zig/std/array_list.zig:263:13: 0x1036d89 in append (zigtest)
            new_item_ptr.* = item;
            ^
src/main.zig:15:21: 0x1036799 in main (zigtest)
    try nodes.append(nodes.items[2]);
                    ^
/usr/lib/zig/std/start.zig:511:37: 0x10365c5 in posixCallMainAndExit (zigtest)
            const result = root.main() catch |err| {
                                    ^
/usr/lib/zig/std/start.zig:253:5: 0x10360e1 in _start (zigtest)
    asm volatile (switch (native_arch) {
    ^
???:?:?: 0x0 in ??? (???)

Expected Behavior

The value should be copied and appended to the newly allocated memory.

Since nodes.items[2] is passed by reference internally, it points to invalidated memory when the ArrayList resizes. This causes the segfault when copying from the invalidated pointer to the new memory.

@nohenry nohenry added the bug Observed behavior contradicts documented or intended behavior label Mar 7, 2024
@Vexu
Copy link
Member

Vexu commented Mar 8, 2024

Duplicate of #19011

@Vexu Vexu marked this as a duplicate of #19011 Mar 8, 2024
@Vexu Vexu closed this as not planned Won't fix, can't repro, duplicate, stale Mar 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Observed behavior contradicts documented or intended behavior
Projects
None yet
Development

No branches or pull requests

2 participants