Segmentation fault at address 0x4 using C library

Hi all,

This is my first post so I will introduce myself a little bit.
I’m working on machine vision for industrial applications mostly using C/C++. When I heard about Zig I saw that you didn’t need to use CMake I thought this was something worth to try. And it was, I love it.

So far I’m using it as a test & build system and everything has been smooth till now. I’m having a seg fault with the following code:

const std = @import("std");
const neurala = @cImport(@cInclude("neurala/api/c/inspectorlib.h"));

pub fn main() void {
    const model_path = "D:/Back_v2.zip";
    var model: ?*neurala.neurala_brain = undefined;

    std.debug.print("Loading model...", .{});
    const status = neurala.neurala_create_brain_from_path(model_path, &model);
    defer neurala.neurala_free_brain(model);

    if (status == neurala.NEURALA_ERRC_OK) {
        std.debug.print("Loading was OK", .{});
    } else {
        std.debug.print("Got error: {d} ", .{status});
    }
}

If I do the same in C compiling it with Zig, it works fine:

int main(int argc, char **argv) {

	char *model_path = "D:\\Back_v2.zip";

	printf("Loading Model: %s\n", model_path);
	neurala_brain* brain;
	neurala_error_code code = neurala_create_brain_from_path(model_path, &brain);
	if (code == NEURALA_ERRC_OK) {
		printf("Model loaded sucessfully: %s\n", model_path);
	}
	else {
		printf("Error loading model: %i\n", code);
	}
	neurala_free_brain(brain);
}

And the build.zig file is:

const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const c_example = b.addExecutable(.{
        .name = "c_example",
        .target = target,
        .optimize = optimize,
    });

    c_example.addCSourceFile(.{ .file = .{ .path = "src/example_api.c" } });
    c_example.addIncludePath(.{ .path = "C:/Program Files/Neurala/InspectorLib/include" });
    c_example.addLibraryPath(.{ .path = "C:/Program Files/Neurala/InspectorLib/lib" });
    c_example.linkSystemLibrary("NeuralaInspectorLib");
    c_example.linkLibC();
    b.installArtifact(c_example);

    const zig_example = b.addExecutable(.{ .name = "zig_example", .target = target, .optimize = optimize, .root_source_file = .{ .path = "src/example_api.zig" } });
    zig_example.addIncludePath(.{ .path = "C:/Program Files/Neurala/InspectorLib/include" });
    zig_example.addLibraryPath(.{ .path = "C:/Program Files/Neurala/InspectorLib/lib" });
    zig_example.linkSystemLibrary("NeuralaInspectorLib");
    zig_example.linkLibC();
    b.installArtifact(zig_example);
}

The error I get when I execute the zig_example.exe is:

PS D:\Devel\Neurala\zig_test\zig-out\bin> .\zig_example.exe
Loading model...Segmentation fault at address 0x4
???:?:?: 0x7ffd0f1a4a3c in ??? (KERNELBASE.dll)
???:?:?: 0x7ffcc0a9d71b in ??? (gna.dll)
???:?:?: 0x7ffcc0a9d3a9 in ??? (gna.dll)
???:?:?: 0x7ffcc0aa034f in ??? (gna.dll)
???:?:?: 0x7ffcc0aa1ace in ??? (gna.dll)
???:?:?: 0x7ffcc0aa1b6e in ??? (gna.dll)
???:?:?: 0x7ffcc0a0c461 in ??? (gna.dll)
???:?:?: 0x7ffcc0a0c3d3 in ??? (gna.dll)
???:?:?: 0x7ffcc0a0c2ef in ??? (gna.dll)
???:?:?: 0x7ffcc0a0a6e1 in ??? (gna.dll)
???:?:?: 0x7ffcc0a0ee5e in ??? (gna.dll)
???:?:?: 0x7ffcc0b27e0d in ??? (???)
???:?:?: 0x7ffcc0c61ba5 in ??? (???)
???:?:?: 0x7ffcc0c62fd1 in ??? (???)
???:?:?: 0x7ffcc0c67f93 in ??? (???)
???:?:?: 0x7ffcc0c4afc1 in ??? (???)
???:?:?: 0x7ffcc0c48792 in ??? (???)
???:?:?: 0x7ffcc66fb8b6 in ??? (???)
???:?:?: 0x7ffcc66f9adb in ??? (???)
???:?:?: 0x7ffce951ffac in ??? (???)
???:?:?: 0x7ffce9521154 in ??? (???)
???:?:?: 0x7ffcc80ad1f0 in ??? (???)
???:?:?: 0x7ffcc80ae2fd in ??? (???)
???:?:?: 0x7ffcc80af78d in ??? (???)
???:?:?: 0x7ffcc80b0720 in ??? (???)
???:?:?: 0x7ffcc8150f10 in ??? (???)
???:?:?: 0x7ffcc815938b in ??? (???)
???:?:?: 0x7ffcc8161176 in ??? (???)
???:?:?: 0x7ffcc821ccb6 in ??? (???)
???:?:?: 0x7ffcc82222dc in ??? (???)
???:?:?: 0x7ffcc821a130 in ??? (???)
???:?:?: 0x7ffcc8206fd3 in ??? (???)
???:?:?: 0x7ffce9413b6c in ??? (???)
???:?:?: 0x7ffce941770e in ??? (???)
D:\Devel\Neurala\zig_test\src\example_api.zig:9:58: 0xc013df in main (zig_example.exe.obj)
    const status = neurala.neurala_create_brain_from_path(model_path, &model);

In the header, the neurala_brain type is defined as:

typedef void* neurala_brain;

I think it’s related to how I’ve defined the model on the zig file but I don’t know how to do it.

var model: ?*neurala.neurala_brain = undefined;

Do you have any idea how I can get more information or how to solve it?

Thank you comunity!
Genís

EDIT: I’m debugging both executables (zig and c examples) and it seems ,in zig, the model variable appears as undefined whereas the c example has a valid address. Can this be related to some optimization on the zig executable?

1 Like

Hi @niso Welcome to ziggit :slight_smile:

D:\Devel\Neurala\zig_test\src\example_api.zig:9:58: 0xc013df in main (zig_example.exe.obj)
    const status = neurala.neurala_create_brain_from_path(model_path, &model);

The crash starts by calling neurala_create_brain_from_path at line 9 of file example_api.zig that is printed at the end of the stack trace.

The model_path argument to this function differs between C and Zig versions.
In zig it is: const model_path = "D:/Back_v2.zip";
In C it is: char *model_path = "D:\\Back_v2.zip";

The problem might be the slash instead of the double backslash.

Hi @dimdin thanks for the quick answer!

Unfortunately it’s still happening the same…

I forgot to show the signature of the function. Here it is:

	neurala_error_code neurala_create_brain_from_path(const char* brain_path, neurala_brain** out_brain);

Do you really want to leave this undefined (that is, having no actual value), or do you want to set it to null?

2 Likes

I actually prefer to have it null but the result is the same. When I pass the pointer to the function it throws a segfault…

Try to declare the model_path as a zero terminated slice ([:0]const u8) and pass the pointer of the slice (model_path.ptr) for path:

const model_path: [:0]const u8 = "D:\\Back_v2.zip";
...
const status = neurala.neurala_create_brain_from_path(model_path.ptr, &model);

Still the same.
I don’t think the error comes from the model_path. In fact If I provide a file that does not exist, the program does not throw a segfault and gives a FileNotFound error code…

Is everything, besides the following include, before C main?

#include "neurala/api/c/inspectorlib.h"

This and stdio.h. This is the full code:

#include <stdio.h>
#include "neurala/api/c/inspectorlib.h"

int main(int argc, char **argv) {

	char *model_path = "D:\\Back_v2.zip";

	printf("Loading Model: %s\n", model_path);
	neurala_brain* brain;
	neurala_error_code code = neurala_create_brain_from_path(model_path, &brain);
	if (code == NEURALA_ERRC_OK) {
		printf("Model loaded sucessfully: %s\n", model_path);
	}
	else {
		printf("Error loading model: %i\n", code);
	}
	neurala_free_brain(brain);
}

It is still more extrange. Here you have a repo with the full code:

Test and zig executable are throwing a seg fault at address 0x4. The weird thing is that the test is calling the same function that I’m using on the C example and it’s working fine.
I’ve also tested in all the release modes and the results are the same…

What happens if you use the msvc abi?

zig build -Dtarget=x86_64-windows-msvc

(the default abi is gnu which is MinGW)

It seems it’s not available.
Right now I’m using “version”: “0.13.0-dev.274+c0da92f71” because I upgraded it yesterday from the 0.12 stable version.
Is there something I need to do to have the msvc version? (I already have VS2022 installed on this computer…)

EDIT: I came back to 0.12 stable and this is the environment:

{
 "zig_exe": "C:\\Users\\MYUSER\\AppData\\Roaming\\Code\\User\\globalStorage\\ziglang.vscode-zig\\zig_install\\zig.exe",
 "lib_dir": "AppData\\Roaming\\Code\\User\\globalStorage\\ziglang.vscode-zig\\zig_install\\lib",
 "std_dir": "AppData\\Roaming\\Code\\User\\globalStorage\\ziglang.vscode-zig\\zig_install\\lib\\std",
 "global_cache_dir": "C:\\Users\\MYUSER\\AppData\\Local\\zig",
 "version": "0.12.0",
 "target": "x86_64-windows.win10_fe...win10_fe-gnu",
 "env": {
  "ZIG_GLOBAL_CACHE_DIR": null,
  "ZIG_LOCAL_CACHE_DIR": null,
  "ZIG_LIB_DIR": null,
  "ZIG_LIBC": null,
  "ZIG_BUILD_RUNNER": null,
  "ZIG_VERBOSE_LINK": null,
  "ZIG_VERBOSE_CC": null,
  "ZIG_BTRFS_WORKAROUND": null,
  "ZIG_DEBUG_CMD": null,
  "CC": null,
  "NO_COLOR": null,
  "XDG_CACHE_HOME": null,
  "HOME": null
 }
}

The intention is for Zig to be able to detect your MSVC install. However, there was a semi-recent fix for the detection code (https://github.com/ziglang/zig/pull/19926) but it would be included in 0.13.0-dev.274+c0da92f71 (but not 0.12.0).

Would you mind downloading vswhere and running:

vswhere -latest -property "installationPath"

?

Just want to confirm that vswhere can find your MSVC installation.

Hi @squeek502 ,

Just installed vswhere through winget and the result returns nothing.
Does this mean that my MSVC installation is corrupt or something? I’ve been using it for more than a year withtout any issue…

1 Like

Here’s what both vswhere and Zig are doing to detect MSVC installs if you want to see what might be going wrong:

  • Checks the CachePath value of HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\Setup within the registry (see regedit). This only exists if your _Instances directory is in a non-standard location, so it not existing is not necessarily a problem
  • If there is no CachePath registry value, the default location of the _Instances directory is %PROGRAMDATA%\Microsoft\VisualStudio\Packages\_Instances
  • Within the _Instances directory, there is a subdirectory for each MSVC install
  • Within each subdirectory, there is a state.json that contains all the information about the installation (e.g. the installationPath key which is what vswhere -property "installationPath" would read from)

So there are a few possibilities for what’s going wrong:

  • Can’t find the _Instances directory or it doesn’t exist
  • No instance subdirectories within _Instances
  • Invalid or missing state.json file within the instance subdirectory for your install
  • Some other state.json-related problem

There was a problem on VS side. I did a repair and now vswhere is returning data. I’m not in front of the laptop. I’ll post the output later.

Thank you for your time!!

After doing a “repair” on Visual studio installer now I get the following on the command you wrote last week:

vswhere -latest -property "installationPath"
C:\Program Files\Microsoft Visual Studio\2022\Professional

And now zig finds the msvc target but it fails to build:

PS D:\Devel\Neurala\zig_test> zig build -Dtarget=x86_64-windows-msvc
install
└─ install c_example
   └─ zig build-exe c_example Debug x86_64-windows-msvc failure
error: the following command exited with error code 5:
C:\Users\USER\AppData\Roaming\Code\User\globalStorage\ziglang.vscode-zig\zig_install\zig.exe build-exe D:\Devel\Neurala\zig_test\src\test.c D:\Devel\Neurala\zig_test\src\example_api.c -lNeuralaInspectorLib -ODebug -target x86_64-windows-msvc -mcpu baseline -I C:\Program Files\Neurala\InspectorLib\include -L C:\Program Files\Neurala\InspectorLib\lib -Mroot -lc --cache-dir D:\Devel\Neurala\zig_test\.zig-cache --global-cache-dir C:\Users\USER\AppData\Local\zig --name c_example --listen=-
install
└─ install zig_example
   └─ zig build-exe zig_example Debug x86_64-windows-msvc failure
error: the following command exited with error code 5:
C:\Users\USER\AppData\Roaming\Code\User\globalStorage\ziglang.vscode-zig\zig_install\zig.exe build-exe -lNeuralaInspectorLib -ODebug -target x86_64-windows-msvc -mcpu baseline -I D:\Devel\Neurala\zig_test\include -I C:\Program Files\Neurala\InspectorLib\include -L C:\Program Files\Neurala\InspectorLib\lib -Mroot=D:\Devel\Neurala\zig_test\src\example_api.zig -lc --cache-dir D:\Devel\Neurala\zig_test\.zig-cache --global-cache-dir C:\Users\USER\AppData\Local\zig --name zig_example --listen=-
Build Summary: 0/5 steps succeeded; 2 failed (disable with --summary none)
install transitive failure
├─ install c_example transitive failure
│  └─ zig build-exe c_example Debug x86_64-windows-msvc failure
└─ install zig_example transitive failure
   └─ zig build-exe zig_example Debug x86_64-windows-msvc failure
error: the following build command failed with exit code 1:
D:\Devel\Neurala\zig_test\.zig-cache\o\223d70a13bdc2786a1b58ab22e2b8f0f\build.exe C:\Users\USER\AppData\Roaming\Code\User\globalStorage\ziglang.vscode-zig\zig_install\zig.exe D:\Devel\Neurala\zig_test D:\Devel\Neurala\zig_test\.zig-cache C:\Users\USER\AppData\Local\zig --seed 0x4245b21e -Z1fa9c754a16f6933 -Dtarget=x86_64-windows-msvc

BTW, I’m using the nightly version and right now it is 0.13.0-dev.346+e54fcdb5b.

Hm, not sure why the errors are so vague.

Can you try running one of the failing commands directly to see if it gives more info? Remove the --listen=- from the command, though, so:

C:\Users\USER\AppData\Roaming\Code\User\globalStorage\ziglang.vscode-zig\zig_install\zig.exe build-exe -lNeuralaInspectorLib -ODebug -target x86_64-windows-msvc -mcpu baseline -I D:\Devel\Neurala\zig_test\include -I C:\Program Files\Neurala\InspectorLib\include -L C:\Program Files\Neurala\InspectorLib\lib -Mroot=D:\Devel\Neurala\zig_test\src\example_api.zig -lc --cache-dir D:\Devel\Neurala\zig_test\.zig-cache --global-cache-dir C:\Users\USER\AppData\Local\zig --name zig_example

This is the error I get:
error: unrecognized file extension of parameter 'Files\Neurala\InspectorLib\include'

The path: Program Files has split with white space.

Probably, you’ll need to quote the path with double-quotation.

1 Like