Skip to content

slice memory corruption on method call #13663

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
hundredwatt opened this issue Nov 27, 2022 · 4 comments
Closed

slice memory corruption on method call #13663

hundredwatt opened this issue Nov 27, 2022 · 4 comments
Labels
bug Observed behavior contradicts documented or intended behavior

Comments

@hundredwatt
Copy link

hundredwatt commented Nov 27, 2022

Zig Version

0.11.0-dev.251+7c527c6df

Steps to Reproduce and Observed Behavior

const std = @import("std");

fn unwrap(slice: []i32) i32 {
    // Commenting out this line fixes the output on Line 25:
    // std.debug.print("\n eval arg: {any}\n", .{slice[0]});
    return slice[0];
}

fn wrap(value: i32) []i32 {
    var arr: [1]i32 = undefined;
    arr[0] = value;

    // return arr[0..]; // same output
    return &arr;
}

pub fn main() void {
    var original: i32 = 255;
    var wrapped = wrap(original);

    std.debug.print("{}, {}\n", .{ original, wrapped[0] }); // prints '255, 255' as expected

    var unwrapped = unwrap(wrapped);

    std.debug.print("{}, {}\n", .{ original, unwrapped }); // prints '255, 3' unless Line 5 is commented out
}
$ zig run src/main.zig
255, 255
255, 3

Expected Behavior

A compiler error to prevent dangling pointer

@hundredwatt hundredwatt added the bug Observed behavior contradicts documented or intended behavior label Nov 27, 2022
@InKryption
Copy link
Contributor

The result of wrap is a dangling pointer to arr. That is to say, after the function returns, arr is popped off the stack, and gets overwritten by other memory e.g. variables declared in later functions using the same stack. This is undefined behavior, not a bug.

@hundredwatt
Copy link
Author

Should this have been prevented with a compiler error?

@InKryption
Copy link
Contributor

InKryption commented Nov 27, 2022

There is ongoing discussion about that. There was a pull request adding such a compile error, but it wasn't merged as it is unclear how to write it into the spec for now.
Related: #5725, #11153

@hundredwatt
Copy link
Author

Closing as dup of #5725. Thank you @InKryption

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