Panic when printing after Raylib's InitWindow()

Hello fellow Zig fans!

First of all, thanks for this amazing language! It’s easy to use and it compiles fast (unlike some other languages).

So, I’ve been experimenting with Zig and Raylib for some time and came across what I can only assume to be a bug.

Here’s a minimal reproducer.

const rl = @cImport(@cInclude("raylib.h"));
const print = @import("std").debug.print;

pub fn main() void {
  print("Before InitWindow()\n", .{});
  rl.InitWindow(300, 200, "Test");
  print("After InitWindow()\n", .{});
  rl.CloseWindow();
}

Write to main.zig and run:

zig run --library "c" --library "raylib" main.zig

It should work just fine.

Now, comment out the first print() statement and re-run.
There is the usual Raylib output, but then, the program panics with the following message.

thread 16078 panic: attempt to use null value

Note that it also happens with the following as print functions:

  • std.log.info
  • std.log.debug

Environment:

  • Zig version: 0.16.0 (via Nixpkgs)
  • Raylib version: 6.0 (via Nixpkgs)
  • Target: x86_64-linux
  • Graphical: Sway (Wayland)

Unless I print at least once before InitWindow(), any call to print() will trigger a panic.
Unfortunately, I don’t know how to take my investigation further, hence this post.

That being said, I suspect it might be related to the following…

Your input would be appreciated. Thank you!

The fact that the early print statement prevents a crash strongly suggests that you’re hitting the same bug as the one from the thread you linked.

https://codeberg.org/ziglang/zig/issues/35512

To work around the bug without actually printing anything to the console, you can add these two statements to the very top of your main function:

 const rl = @cImport(@cInclude("raylib.h"));
 const print = @import("std").debug.print;
 
 pub fn main() void {
-    print("Before InitWindow()\n", .{});
+    std.debug.lockStderr(&.{});
+    std.debug.unlockStderr();
     rl.InitWindow(300, 200, "Test");
     print("After InitWindow()\n", .{});
     rl.CloseWindow();
 }