C Strings in Zig
In Why Zig Over C for Systems Programming I wrote that a Zig string is a slice of bytes with a length, so there is no 0 byte at the end to forget. That is true until you call a C function because the C standard library and almost every other C library that I use expect a pointer to bytes that end with a 0. In this post I put the cases that I meet in one program and then explain what I do in each one. I shortened the compiler errors and the stack traces to keep the output short.
const std = @import("std");
extern "c" fn strlen(s: [*:0]const u8) usize;
extern "c" fn puts(s: [*:0]const u8) c_int;
extern "c" fn getenv(name: [*:0]const u8) ?[*:0]const u8;
extern "c" fn gethostname(name: [*]u8, len: usize) c_int;
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
// 1. A string literal already ends with a 0 byte
const literal = "Zig";
std.debug.print("{s}: {d} bytes, strlen says {d}\n", .{ literal, literal.len, strlen(literal) });
// 2. A slice does not, so make a copy that does
const path: []const u8 = "/usr/local/bin";
const dir: []const u8 = path[0..4];
const dir_z = try allocator.dupeSentinel(u8, dir, 0);
defer allocator.free(dir_z);
_ = puts(dir_z);
// 3. The same without the heap
var buf: [64]u8 = undefined;
const msg = try std.mem.printSentinel(&buf, "{s} has {d} bytes", .{ dir, dir.len }, 0);
_ = puts(msg);
// 4. A C string that comes back from C
if (getenv("SHELL")) |shell_ptr| {
const shell: [:0]const u8 = std.mem.span(shell_ptr);
std.debug.print("SHELL is {s} ({d} bytes)\n", .{ shell, shell.len });
}
// 5. A buffer that C fills in
var host_buf: [256]u8 = undefined;
if (gethostname(&host_buf, host_buf.len) == 0) {
const host = std.mem.sliceTo(&host_buf, 0);
std.debug.print("host name has {d} bytes\n", .{host.len});
}
// 6. A 0 byte in the middle
const odd = "abc\x00def";
std.debug.print("len {d}, strlen {d}\n", .{ odd.len, strlen(odd) });
if (std.mem.findScalar(u8, odd, 0)) |pos| {
std.debug.print("found a 0 byte at position {d}\n", .{pos});
}
}
A sentinel is a known value that is stored right after the last element of an array or a slice to mark where it ends. For a C string the sentinel is a 0 byte. Zig puts the sentinel in the type. The [*:0]const u8 type is a pointer to an unknown number of bytes that end with a 0, which is what C calls a const char *. The [:0]const u8 type is a slice, so it has a pointer and a length and it also promises that there is a 0 right after the last byte. The length does not count the 0. A C function that is declared with [*:0]const u8 accepts only a pointer whose type has the sentinel. An ordinary slice such as []const u8 does not have it, so passing one to such a function is a compile error.
I declared the four C functions by hand with these types to keep the program in one file. For a real C library I would create the declarations from its header files with zig translate-c. Those declarations use a different pointer type and I show what that means for strings in a section of its own below.
A string literal such as "Zig" has the type *const [3:0]u8, so the compiler always stores a 0 after it and the first call to strlen() works without any conversion. The same is true for getenv("SHELL"). The literal.len value is 3 and it is known at compile time, while strlen() has to walk the bytes to find the same number.
The path[0..4] expression gives a slice with the bytes /usr. The byte after it is the / of /local, so this slice is not a C string and Zig does not let me pass it to puts(). The dupeSentinel() function of the allocator makes a copy with one extra byte for the 0 and returns a [:0]u8, which I have to free like any other allocation. When the string is short and I know its maximum size, I use std.mem.printSentinel() with a buffer on the stack and there is no allocation at all. It returns error.NoSpaceLeft if the text and the 0 do not fit in the buffer. Before Zig 0.17 the dupeSentinel() function was named dupeZ() and the std.mem.printSentinel() function was named std.fmt.bufPrintZ().
The getenv() function returns a pointer or NULL, so its Zig return type is ?[*:0]const u8 and the if deals with the case where the variable is not set. The std.mem.span() function finds the 0 and returns a [:0]const u8 with a proper length. It does not copy anything. The bytes still belong to the environment, so if I want to keep the string I make my own copy with allocator.dupe().
The gethostname() function is the other direction, where I give C a buffer and C writes a string in it. After the call the buffer has the name, a 0 and then whatever was there before. The std.mem.sliceTo() function returns the part of the buffer before the first 0. It also never reads past the end of the buffer. I show why I need that in the section about a buffer that is too small.
A Zig string can have a 0 byte in the middle because its length does not depend on the contents. The odd string has 7 bytes, which are abc, a 0 and def. The odd.len value is 7 but strlen() stops at the first 0 and returns 3. If such a string goes to C, the C code sees only abc and never reaches the def that comes after the 0. When the bytes come from a file or from the network, I check for a 0 with std.mem.findScalar() before I pass them to C, which is what the last lines of the program do. The function returns the position of the first 0 or null when there is none.
Save the code as cstrings.zig and run it. The -lc option links the C library. On macOS the C library is always linked but on Linux you need it:
$ zig version
0.17.1
$ zig run -lc cstrings.zig
Zig: 3 bytes, strlen says 3
/usr
/usr has 4 bytes
SHELL is /bin/zsh (8 bytes)
host name has 8 bytes
len 7, strlen 3
found a 0 byte at position 3
A slice is not a C string Link to heading
The mistake I made most often was to pass the ptr field of an ordinary slice to a C function:
const std = @import("std");
extern "c" fn puts(s: [*:0]const u8) c_int;
pub fn main() void {
const path: []const u8 = "/usr/local/bin";
const dir: []const u8 = path[0..4];
_ = puts(dir.ptr);
}
$ zig run -lc notz.zig
notz.zig:8:17: error: expected type '[*:0]const u8', found '[*]const u8'
_ = puts(dir.ptr);
~~~^~~~
notz.zig:8:17: note: destination pointer requires '0' sentinel
In C the same call compiles and prints /usr/local/bin because puts() keeps going until it finds a 0. In this program there happens to be one a few bytes later. With a buffer that was read from a file there may not be one for a long time. Zig stops this at compile time because the type of dir.ptr does not say that the bytes end with a 0.
Declarations from zig translate-c Link to heading
For a big C library I do not write the declarations by hand. The zig translate-c command reads a C header file and prints the same declarations as Zig code, as I showed in @cImport() Is gone in Zig 0.17. The declarations that it creates do not give the compile error of the previous section. To see why, I created a file named c.h with the following four lines:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
Then I looked at what the command made of the four functions of this post on my Mac:
$ zig translate-c -lc c.h > c.zig
$ grep -E "fn (puts|strlen|getenv|gethostname)\(" c.zig
pub extern fn puts([*c]const u8) c_int;
pub extern fn getenv([*c]const u8) [*c]u8;
pub extern fn strlen(__s: [*c]const u8) usize;
pub extern fn gethostname([*c]u8, __namelen: usize) c_int;
None of them has [*:0]const u8. The [*c]const u8 type is a C pointer, which is a pointer type that Zig has only for translated C code. The command has to use it because const char * in a C header file can mean a pointer to one byte, a pointer to an array of bytes or a C string and it can also be NULL. The header file does not say which one it is, so a C pointer accepts all of them. That includes the ptr field of an ordinary slice, as the following program shows:
const c = @import("c.zig");
pub fn main() void {
const path: []const u8 = "/usr/local/bin";
const dir: []const u8 = path[0..4];
_ = c.puts(dir.ptr);
}
$ zig run -lc translated.zig
/usr/local/bin
This is the mistake of the previous section with the translated puts(). It compiles because the type of the parameter no longer asks for a 0 at the end and it prints /usr/local/bin instead of /usr, just as it does in C. To get the check back I put the call to the C function inside a small Zig function that takes a [:0]const u8 and I call that function from the rest of my code:
const c = @import("c.zig");
fn putsZ(s: [:0]const u8) void {
_ = c.puts(s.ptr);
}
pub fn main() void {
const path: []const u8 = "/usr/local/bin";
const dir: []const u8 = path[0..4];
putsZ("Zig");
putsZ(dir);
}
$ zig run -lc wrapper.zig
wrapper.zig:11:11: error: expected type '[:0]const u8', found '[]const u8'
putsZ(dir);
^~~
wrapper.zig:11:11: note: destination pointer requires '0' sentinel
The putsZ("Zig") call is accepted because a string literal has the sentinel in its type. The putsZ(dir) call is the compile error that I wanted back. The last version is the one that compiles, where the slice becomes a C string before it goes to putsZ() and the program also reads a string that comes back from C:
const std = @import("std");
const c = @import("c.zig");
fn putsZ(s: [:0]const u8) void {
_ = c.puts(s.ptr);
}
pub fn main() !void {
const path: []const u8 = "/usr/local/bin";
const dir: []const u8 = path[0..4];
var buf: [16]u8 = undefined;
const dir_z = try std.mem.printSentinel(&buf, "{s}", .{dir}, 0);
putsZ(dir_z);
if (c.getenv("SHELL")) |shell_ptr| {
const shell = std.mem.span(shell_ptr);
putsZ(shell);
}
}
$ zig run -lc fixed.zig
/usr
/bin/zsh
The first line is /usr this time. Strings that come back from C need no function of their own. The translated getenv() returns a [*c]u8, the if with a capture still handles NULL and std.mem.span() turns the pointer into a [:0]u8, which putsZ() accepts.
A buffer that is too small Link to heading
The host name of my Mac has 8 bytes. The following program gives gethostname() a buffer of 4 bytes to see what happens when the name does not fit:
const std = @import("std");
extern "c" fn gethostname(name: [*]u8, len: usize) c_int;
pub fn main() void {
var buf: [4]u8 = undefined;
if (gethostname(&buf, buf.len) == 0) {
const host = std.mem.sliceTo(&buf, 0);
std.debug.print("last byte is {d}, the name has {d} bytes\n", .{ buf[3], host.len });
}
}
$ zig run -lc small.zig
last byte is 0, the name has 3 bytes
On my Mac the function wrote the first 3 bytes of the name and put a 0 in the last byte, so the buffer still has a C string that is shorter than the real name. The POSIX standard does not promise the 0. It says that the name is cut when it does not fit and that the 0 may or may not be there, so on another system all 4 bytes of the buffer could be letters of the name.
I cannot make my Mac leave the 0 out, so the next program builds that case by hand. The first 4 bytes of memory are the buffer and they have letters and no 0. The 4 bytes after them stand for whatever comes next in memory:
const std = @import("std");
pub fn main() void {
var memory = [_]u8{ 'a', 'b', 'c', 'd', 'X', 'Y', 'Z', 0 };
const buf = memory[0..4];
const inside = std.mem.sliceTo(buf, 0);
std.debug.print("sliceTo: {s} ({d} bytes)\n", .{ inside, inside.len });
const ptr: [*:0]u8 = @ptrCast(buf);
const outside = std.mem.span(ptr);
std.debug.print("span: {s} ({d} bytes)\n", .{ outside, outside.len });
}
$ zig run nozero.zig
sliceTo: abcd (4 bytes)
span: abcdXYZ (7 bytes)
The std.mem.sliceTo() function gets the buffer itself, so it knows that there are 4 bytes and it stops at the last one. The std.mem.span() function does not accept the buffer at all because its type has no sentinel, so the program needs @ptrCast() to make a [*:0]u8 out of it. After the cast the function has only a pointer and it reads one byte after the other until it finds a 0, which is 3 bytes past the end of the buffer. In a real program those bytes belong to something else.
Slicing with a sentinel Link to heading
Sometimes the 0 is already in my buffer, for example after a C function wrote a string in it. In that case I do not want to make a copy and the buf[0..3 :0] syntax gives a slice with a sentinel that points to the same bytes. It means the bytes from position 0 up to position 3 and it also says that the byte at position 3 is a 0. The following program does that at a position that has a 0 and then at a position that does not:
const std = @import("std");
pub fn main() void {
var buf = [_]u8{ 'a', 'b', 'c', 0, 'd', 'e', 'f', 'g' };
const good = buf[0..3 :0];
std.debug.print("{s} ({d} bytes)\n", .{ good, good.len });
const bad = buf[4..7 :0];
std.debug.print("{s} ({d} bytes)\n", .{ bad, bad.len });
}
$ zig run sentinel.zig
abc (3 bytes)
thread 1904989 panic: sentinel mismatch: expected 0, found 103
sentinel.zig:9:20: 0x1002dc51b in main (sentinel)
const bad = buf[4..7 :0];
^
The first slice is correct because the byte at position 3 is a 0, so the program prints abc. The mistake is in line 9. Positions 4 to 6 have def, so the bytes of the second slice are the right ones. The :0 part is what is wrong because it says that the byte at position 7 is a 0 while it is the letter g, which is the number 103. In the debug and safe modes Zig checks that byte when it makes the slice and stops the program there.
The real problem is in the fast and small modes, where the check is not there and the program prints def (3 bytes) as its second line. That output looks correct, yet the type of bad says that a 0 follows the f and that is not true. Zig does not check it a second time, so every function that asks for a string with a sentinel accepts bad. A C function that got it would read def, then the g and then the memory after the buffer until it found a 0.
Which one Link to heading
- Use
[]const u8for every string that stays in Zig. This is my default. - Use
[:0]const u8for a string that I own and that will go to C. It is still a slice, so the Zig code can use its length. - Use
[*:0]const u8only in the declarations of C functions and turn it into a slice withstd.mem.span()as soon as it arrives. - Use
allocator.dupeSentinel()orstd.mem.printSentinel()when a slice has to become a C string. - Use
std.mem.sliceTo()when C wrote a string into a buffer of mine. - Use a small function that takes a
[:0]const u8around a C function that comes fromzig translate-c, as its[*c]parameters accept any pointer.
If I had to keep one rule, it would be to do the conversion at the call to C and to keep slices everywhere else.
Conclusion Link to heading
Most of this post is about what goes wrong, which may give the impression that Zig does not do well with C strings, while the opposite is true. Passing an ordinary slice to a C function that wants a C string is a compile error and so is passing one to putsZ() or giving std.mem.span() a buffer whose type has no sentinel. When I say that a 0 is at a position where there is none, the program stops at that line in the debug and safe modes and std.mem.sliceTo() never reads past the end of a buffer. The same mistakes in C compile and run. The mistakes that got through in this post did so because I gave up a check myself, by using the declarations of zig translate-c as they are, by writing a @ptrCast() or by building in the fast or small mode. Zig does not make C strings safe but it catches most of the mistakes at compile time and it lets me know where the rest can hide.
Happy coding in Zig!
Want to learn Zig? Look at my book Systems Programming with Zig.