I'm currently learning Zig (having very little experience in C) and I'm doing some experiments with strings to make sure I understand the concept properly.
For example, since strings are arrays of u8
I figured out that I can print the character 'C' using the following code:
std.debug.print("{}", .{[_]u8{67}});
I then tried to make a loop in order to print some basic characters with codes ranging from 33 to 126:
var i: u8 = 33;
while (i < 127) {
std.debug.print("{}", .{[_]u8{i}});
i += 1;
}
But when I run it the following error happens:
Segmentation fault at address 0x202710
/home/cassidy/learning-zig/hello-world/src/main.zig:9:39: 0x22ae15 in main (main)
std.debug.print("{}", .{[_]u8{i}});
^
/snap/zig/2222/lib/zig/std/start.zig:272:37: 0x204b9d in std.start.posixCallMainAndExit (main)
const result = root.main() catch |err| {
^
/snap/zig/2222/lib/zig/std/start.zig:143:5: 0x2048df in std.start._start (main)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
[1] 24766 abort (core dumped) ./main
The strangest thing is that when I change the code a little to create a variable holding the u8
array, then it works as intended:
var i: u8 = 33;
while (i < 127) {
const c = [_]u8{i};
std.debug.print("{}", .{c});
i += 1;
}
Returns:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
Could someone explain why the second code triggers a seg fault?