Skip to content

Suggestion: make returning pointer to stack memory created in the same scope a compiler error #13441

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
Jarred-Sumner opened this issue Nov 4, 2022 · 1 comment

Comments

@Jarred-Sumner
Copy link
Contributor

Jarred-Sumner commented Nov 4, 2022

One spot where Zig lags behind C compilers in memory safety: returning a pointer to a temporary created in the same scope (specifically when the value is not comptime known)

For people new to manual memory management, this is a footgun

In C:

static char *myFunction() {
  char buf[200];
  buf[0] = 'h';
  buf[1] = 'e';
  buf[2] = 'y';
  buf[3] = '!';

  return buf;
}

int main(void) { myFunction(); }

Compile:

$ clang hey.c

hey.c:11:10: warning: address of stack memory associated with local variable 'buf' returned [-Wreturn-stack-address]
  return buf;
         ^~~
1 warning generated.

In Zig:

fn myFunction() []u8 {
    var buf: [100]u8 = undefined;
    buf[0.."hello".len].* = "hello".*;
    return buf[0..];
}

pub fn main() anyerror!void {
  std.mem.doNotOptimizeAway(myFunction());
}

Compile:

$ zig build-exe hey.zig
# no error
@andrewrk
Copy link
Member

andrewrk commented Nov 4, 2022

duplicate of #2646

@andrewrk andrewrk closed this as not planned Won't fix, can't repro, duplicate, stale Nov 4, 2022
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