Skip to content

Zig 0.7.1 allows user to return addresses of local variables #8702

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
LucasToole opened this issue May 7, 2021 · 2 comments
Closed

Zig 0.7.1 allows user to return addresses of local variables #8702

LucasToole opened this issue May 7, 2021 · 2 comments
Milestone

Comments

@LucasToole
Copy link

LucasToole commented May 7, 2021

Contents of a function are still accessible even after their lifetime. For example:

const std = @import("std");

pub fn main() anyerror!void {
    const test_ptr: *i32 = test_func();
    std.debug.print("Address: {}\n", .{test_ptr});
    std.debug.print("Value: {}\n", .{test_ptr.*});
}

fn test_func() *i32 {
    var test_var: i32 = 5;
    return &test_var;
}

Results in:

$ zig run localaddress.zig
Address: i32@7fff157f79a4
Value: 5

The equivalent C code:

#include <stdio.h>

int* test_func() {
	int test_var = 5;
	return &test_var;
}

int main(void) {
	int *test_ptr = test_func();
	printf("Address: %ls\n", test_ptr);
	printf("Value: %d\n", *test_ptr);
	return 0;
}

Produces a compile-time warning:

$ gcc localaddr.c -o localaddr
localaddr.c: In function ‘test_func’:
localaddr.c:5:9: warning: function returns address of local variable [-Wreturn-local-addr]
    5 |  return &test_var;
      |         ^~~~~~~~~

And produces:

$ ./localaddr 
Address: (null)
Segmentation fault
@g-w1
Copy link
Contributor

g-w1 commented May 7, 2021

Dupe of #2646

@LucasToole
Copy link
Author

@g-w1 Oops, sorry about that! I'll do more searching in the future.

@andrewrk andrewrk closed this as completed May 7, 2021
@andrewrk andrewrk added this to the 0.8.0 milestone Jun 4, 2021
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

3 participants