Converting []const u8 to [:0]const u8

So I am trying to convert from []const u8 to [:0]const u8

const string = std.fmt.allocPrint(allocator, "{}", .{game.score}) catch "0";
defer allocator.free(string);
const slice = string[0..string.len:0];
rl.drawText(slice, 10, 10, 24, rl.Color.white);

I am not completely sure what sentinel terminated slices are, but I assume that the zero specifies the end of the string \0. I tried converting from []const u8 to [:0]const u8 as shown in my code, but get this error.

thread 6576 panic: index out of bounds: index 2, len 1
???:?:?: 0x7ff738d635f2 in ??? (???)
???:?:?: 0x7ff738d6165b in ??? (???)
???:?:?: 0x7ff738d6123c in ??? (???)
???:?:?: 0x7ff738dcd094 in ??? (???)
???:?:?: 0x7ff738dcd0eb in ??? (???)
???:?:?: 0x7ff81b267343 in ??? (KERNEL32.DLL)
???:?:?: 0x7ff81bd226b0 in ??? (ntdll.dll)

also tried doing string[0..:0] but got the same error.

1 Like

You can call allocPrintZ to get a zero terminated string.
Also see:

2 Likes

Hi @Cmd, welcome to ziggit!

Simplest way is to just use std.fmt.allocPrintZ, the Z is a convention for functions that return zero terminated strings.

Also notice that there is a problem with your original code if the allocation fails, string gets assigned the string literal value "0" this literal wasn’t dynamically allocated and exists in the read only data section of the executable, however because your code just continues with that literal value, the next line registers a defer to free that literal, this defer will fail when it gets executed (at the end of the scope).

if(std.fmt.allocPrintZ(allocator, "{}", .{game.score})) |score| {
    defer allocator.free(score);
    rl.drawText(score, 10, 10, 24, rl.Color.white);
} else |_| {
    rl.drawText("0", 10, 10, 24, rl.Color.white);
}

To circumvent that you need to avoid mixing dynamic and static data in the same code path, my code above does that by using the if to switch on the error union returned by allocPrintZ, if the allocation works we execute the defer and then draw the text, otherwise we just draw the static literal.

2 Likes

Thanks @dimdin. Ya I did see that question I just could not find anything there for formating []const u8 to [:0]const u8. Also thank you @Sze I did not notice that thank you.

4 Likes