Skip to content

Instantly share code, notes, and snippets.

@manikawnth
Created July 19, 2020 17:26
Show Gist options
  • Save manikawnth/e6444f11733f5a334558d36a0adb7206 to your computer and use it in GitHub Desktop.
Save manikawnth/e6444f11733f5a334558d36a0adb7206 to your computer and use it in GitHub Desktop.
Zig stack mem returned from func printing, but not mutating
const std = @import("std");
const Point = struct {
x: i32,
y: i32,
fn print(self: Point) void {
std.debug.print("x is {}, y is {}\n", .{self.x, self.y});
}
};
pub fn main() void {
var p = Point {.x = 32, .y = 45 };
var copyValPtr: *Point = reverse_facade(p);
copyValPtr.print(); //pointer available here
reverse(copyValPtr); // not available here
copyValPtr.print();
}
fn reverse_facade(p: Point) *Point {
var q = Point{.x = p.x, .y =p.y}; //copy
var ptr = &q;
return ptr; //escapes?
}
fn reverse(p: *Point) void{
const temp = p.y;
p.y = p.x;
p.x = temp;
}
@manikawnth
Copy link
Author

And here is the output

x is 32, y is 45
Segmentation fault at address 0xffffffffffffffff
C:\personal\zigspace\test\hello.zig:31:11: 0x7ff60b42c6ac in reverse (hello.obj)
    p.x = temp;
          ^
C:\personal\zigspace\test\hello.zig:18:12: 0x7ff60b4133c3 in main (hello.obj)
    reverse(copyValPtr); // not available here
           ^
C:\personal\softwares\bin\lib\zig\std\start.zig:134:65: 0x7ff60b411897 in std.start.WinMainCRTStartup (hello.obj)
    std.os.windows.kernel32.ExitProcess(initEventLoopAndCallMain());
                                                                ^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment