2

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?

2 Answers2

1

After asking on the Zig Discord it appears that it is indeed a bug. Hopefully it will be fixed soon since the language is still under heavy development!

0

What you are experiencing is a bug, but it is still possible to print characters

The standard way to do it is with {c} to print a character (or once #6390 is merged, {u} for printing a unicode codepoint as utf-8)

std.debug.print("{c}", .{i});

Also it is possible to print with [_]u8{i} if you address-of it first so it is *const [1]u8 instead of [1]u8

std.debug.print("{}", .{&[_]u8{i}});
pfg
  • 2,348
  • 1
  • 16
  • 37