-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdangling_pointer.zig
More file actions
44 lines (32 loc) · 797 Bytes
/
dangling_pointer.zig
File metadata and controls
44 lines (32 loc) · 797 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const std = @import("std");
pub fn main() !void {
var p = pointer();
// here it works, which is a bit unexpected
std.debug.print("{s}\n", .{p.msg});
// (core dump) but here it won't as expected, I don't
// understand well why it works in the previous case.
printMsg(p);
var p2 = constPointer();
// here it works too
std.debug.print("{s}\n", .{p2.msg});
// (core dump) but here it won't either
printMsg(p);
}
const MyStruct = struct {
msg: []const u8,
};
fn pointer() *MyStruct {
var m = MyStruct{
.msg = "hello",
};
return &m;
}
fn constPointer()*const MyStruct{
const m = MyStruct{
.msg = "world",
};
return &m;
}
fn printMsg(p: *const MyStruct) void {
std.debug.print("{s}\n", .{p.msg});
}