- Undefined Behavior
- Reaching Unreachable Code
- Index out of Bounds
- Cast Negative Number to Unsigned Integer
- Cast Truncates Data
- Integer Overflow
- Exact Left Shift Overflow
- Exact Right Shift Overflow
- Division by Zero
- Remainder Division by Zero
- Exact Division Remainder
- Attempt to Unwrap Null
- Attempt to Unwrap Error
- Invalid Error Code
- Invalid Enum Cast
- Invalid Error Set Cast
- Incorrect Pointer Alignment
- Wrong Union Field Access
- Out of Bounds Float to Integer Cast
- Pointer Cast Invalid Null
Undefined Behavior
Zig has many instances of undefined behavior. If undefined behavior is detected at compile-time, Zig emits a compile error and refuses to continue. Most undefined behavior that cannot be detected at compile-time can be detected at runtime. In these cases, Zig has safety checks. Safety checks can be disabled on a per-block basis with @setRuntimeSafety. The ReleaseFast and ReleaseSmall build modes disable all safety checks (except where overridden by @setRuntimeSafety) in order to facilitate optimizations.
When a safety check fails, Zig crashes with a stack trace, like this:
test.zig
test "safety check" {
unreachable;
}
Shell
$ zig test test.zig
1/1 test.safety check... thread 3584529 panic: reached unreachable code
docgen_tmp/test.zig:2:5: 0x211565 in test.safety check (test)
unreachable;
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/test_runner.zig:63:28: 0x212cf3 in main (test)
} else test_fn.func();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x211e7c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x211981 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
error: the following test command crashed:
/home/ci/release-0.10.1/out/zig-local-cache/o/886dbde2c2a21074c6c6d3ff9b83336b/test
Reaching Unreachable Code
At compile-time:
test.zig
comptime {
assert(false);
}
fn assert(ok: bool) void {
if (!ok) unreachable; // assertion failure
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:5:14: error: reached unreachable code
if (!ok) unreachable; // assertion failure
^~~~~~~~~~~
docgen_tmp/test.zig:2:11: note: called from here
assert(false);
~~~~~~^~~~~~~
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
std.debug.assert(false);
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3584625 panic: reached unreachable code
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/debug.zig:278:14: 0x211a0c in assert (test)
if (!ok) unreachable; // assertion failure
^
docgen_tmp/test.zig:4:21: 0x21015a in main (test)
std.debug.assert(false);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f6ec in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f1f1 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Index out of Bounds
At compile-time:
test.zig
comptime {
const array: [5]u8 = "hello".*;
const garbage = array[5];
_ = garbage;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:3:27: error: index 5 outside array of length 5
const garbage = array[5];
^
At runtime:
test.zig
pub fn main() void {
var x = foo("hello");
_ = x;
}
fn foo(x: []const u8) u8 {
return x[5];
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3584735 panic: index out of bounds: index 5, len 5
docgen_tmp/test.zig:7:13: 0x211cea in foo (test)
return x[5];
^
docgen_tmp/test.zig:2:16: 0x21016b in main (test)
var x = foo("hello");
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f6ec in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f1f1 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Cast Negative Number to Unsigned Integer
At compile-time:
test.zig
comptime {
var value: i32 = -1;
const unsigned = @intCast(u32, value);
_ = unsigned;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:3:36: error: type 'u32' cannot represent integer value '-1'
const unsigned = @intCast(u32, value);
^~~~~
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var value: i32 = -1;
var unsigned = @intCast(u32, value);
std.debug.print("value: {}\n", .{unsigned});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3584859 panic: attempt to cast negative value to unsigned integer
docgen_tmp/test.zig:5:20: 0x21036d in main (test)
var unsigned = @intCast(u32, value);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f8cc in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f3d1 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
To obtain the maximum value of an unsigned integer, use std.math.maxInt
.
Cast Truncates Data
At compile-time:
test.zig
comptime {
const spartan_count: u16 = 300;
const byte = @intCast(u8, spartan_count);
_ = byte;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:3:31: error: type 'u8' cannot represent integer value '300'
const byte = @intCast(u8, spartan_count);
^~~~~~~~~~~~~
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var spartan_count: u16 = 300;
const byte = @intCast(u8, spartan_count);
std.debug.print("value: {}\n", .{byte});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3584984 panic: integer cast truncated bits
docgen_tmp/test.zig:5:18: 0x210326 in main (test)
const byte = @intCast(u8, spartan_count);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f87c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f381 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
To truncate bits, use @truncate.
Integer Overflow
Default Operations
The following operators can cause integer overflow:
+
(addition)-
(subtraction)-
(negation)*
(multiplication)/
(division)- @divTrunc (division)
- @divFloor (division)
- @divExact (division)
Example with addition at compile-time:
test.zig
comptime {
var byte: u8 = 255;
byte += 1;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:3:10: error: overflow of integer type 'u8' with value '256'
byte += 1;
~~~~~^~~~
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var byte: u8 = 255;
byte += 1;
std.debug.print("value: {}\n", .{byte});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3585038 panic: integer overflow
docgen_tmp/test.zig:5:10: 0x210314 in main (test)
byte += 1;
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f86c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f371 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Standard Library Math Functions
These functions provided by the standard library return possible errors.
@import("std").math.add
@import("std").math.sub
@import("std").math.mul
@import("std").math.divTrunc
@import("std").math.divFloor
@import("std").math.divExact
@import("std").math.shl
Example of catching an overflow for addition:
test.zig
const math = @import("std").math;
const print = @import("std").debug.print;
pub fn main() !void {
var byte: u8 = 255;
byte = if (math.add(u8, byte, 1)) |result| result else |err| {
print("unable to add one: {s}\n", .{@errorName(err)});
return err;
};
print("result: {}\n", .{byte});
}
Shell
$ zig build-exe test.zig
$ ./test
unable to add one: Overflow
error: Overflow
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/math.zig:484:5: 0x210131 in add__anon_2905 (test)
return if (@addWithOverflow(T, a, b, &answer)) error.Overflow else answer;
^
docgen_tmp/test.zig:8:9: 0x210024 in main (test)
return err;
^
Builtin Overflow Functions
These builtins return a bool
of whether or not overflow occurred, as well as returning the overflowed bits:
Example of @addWithOverflow:
test.zig
const print = @import("std").debug.print;
pub fn main() void {
var byte: u8 = 255;
var result: u8 = undefined;
if (@addWithOverflow(u8, byte, 10, &result)) {
print("overflowed result: {}\n", .{result});
} else {
print("result: {}\n", .{result});
}
}
Shell
$ zig build-exe test.zig
$ ./test
overflowed result: 9
Wrapping Operations
These operations have guaranteed wraparound semantics.
+%
(wraparound addition)-%
(wraparound subtraction)-%
(wraparound negation)*%
(wraparound multiplication)
wraparound_semantics.zig
const std = @import("std");
const expect = std.testing.expect;
const minInt = std.math.minInt;
const maxInt = std.math.maxInt;
test "wraparound addition and subtraction" {
const x: i32 = maxInt(i32);
const min_val = x +% 1;
try expect(min_val == minInt(i32));
const max_val = min_val -% 1;
try expect(max_val == maxInt(i32));
}
Shell
$ zig test wraparound_semantics.zig
1/1 test.wraparound addition and subtraction... OK
All 1 tests passed.
Exact Left Shift Overflow
At compile-time:
test.zig
comptime {
const x = @shlExact(@as(u8, 0b01010101), 2);
_ = x;
}
Shell
$ zig test test.zig -fstage1
./docgen_tmp/test.zig:2:15: error: operation caused overflow
const x = @shlExact(@as(u8, 0b01010101), 2);
^
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var x: u8 = 0b01010101;
var y = @shlExact(x, 2);
std.debug.print("value: {}\n", .{y});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3585355 panic: left shift overflowed bits
docgen_tmp/test.zig:5:13: 0x21032a in main (test)
var y = @shlExact(x, 2);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f87c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f381 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Exact Right Shift Overflow
At compile-time:
test.zig
comptime {
const x = @shrExact(@as(u8, 0b10101010), 2);
_ = x;
}
Shell
$ zig test test.zig -fstage1
./docgen_tmp/test.zig:2:15: error: exact shift shifted out 1 bits
const x = @shrExact(@as(u8, 0b10101010), 2);
^
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var x: u8 = 0b10101010;
var y = @shrExact(x, 2);
std.debug.print("value: {}\n", .{y});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3585494 panic: right shift overflowed bits
docgen_tmp/test.zig:5:13: 0x210321 in main (test)
var y = @shrExact(x, 2);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f87c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f381 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Division by Zero
At compile-time:
test.zig
comptime {
const a: i32 = 1;
const b: i32 = 0;
const c = a / b;
_ = c;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:4:19: error: division by zero here causes undefined behavior
const c = a / b;
^
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var a: u32 = 1;
var b: u32 = 0;
var c = a / b;
std.debug.print("value: {}\n", .{c});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3585604 panic: division by zero
docgen_tmp/test.zig:6:15: 0x21034a in main (test)
var c = a / b;
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f89c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f3a1 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Remainder Division by Zero
At compile-time:
test.zig
comptime {
const a: i32 = 10;
const b: i32 = 0;
const c = a % b;
_ = c;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:4:19: error: division by zero here causes undefined behavior
const c = a % b;
^
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var a: u32 = 10;
var b: u32 = 0;
var c = a % b;
std.debug.print("value: {}\n", .{c});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3585672 panic: division by zero
docgen_tmp/test.zig:6:15: 0x21034a in main (test)
var c = a % b;
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f89c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f3a1 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Exact Division Remainder
At compile-time:
test.zig
comptime {
const a: u32 = 10;
const b: u32 = 3;
const c = @divExact(a, b);
_ = c;
}
Shell
$ zig test test.zig -fstage1
./docgen_tmp/test.zig:4:15: error: exact division had a remainder
const c = @divExact(a, b);
^
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var a: u32 = 10;
var b: u32 = 3;
var c = @divExact(a, b);
std.debug.print("value: {}\n", .{c});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3585768 panic: exact division produced remainder
docgen_tmp/test.zig:6:13: 0x2103b9 in main (test)
var c = @divExact(a, b);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f8cc in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f3d1 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Attempt to Unwrap Null
At compile-time:
test.zig
comptime {
const optional_number: ?i32 = null;
const number = optional_number.?;
_ = number;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:3:35: error: unable to unwrap null
const number = optional_number.?;
~~~~~~~~~~~~~~~^~
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var optional_number: ?i32 = null;
var number = optional_number.?;
std.debug.print("value: {}\n", .{number});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3585872 panic: attempt to use null value
docgen_tmp/test.zig:5:33: 0x210405 in main (test)
var number = optional_number.?;
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f95c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f461 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
One way to avoid this crash is to test for null instead of assuming non-null, with the if
expression:
test.zig
const print = @import("std").debug.print;
pub fn main() void {
const optional_number: ?i32 = null;
if (optional_number) |number| {
print("got number: {}\n", .{number});
} else {
print("it's null\n", .{});
}
}
Shell
$ zig build-exe test.zig
$ ./test
it's null
See also:
Attempt to Unwrap Error
At compile-time:
test.zig
comptime {
const number = getNumberOrFail() catch unreachable;
_ = number;
}
fn getNumberOrFail() !i32 {
return error.UnableToReturnNumber;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:2:44: error: caught unexpected error 'UnableToReturnNumber'
const number = getNumberOrFail() catch unreachable;
^~~~~~~~~~~
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
const number = getNumberOrFail() catch unreachable;
std.debug.print("value: {}\n", .{number});
}
fn getNumberOrFail() !i32 {
return error.UnableToReturnNumber;
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3586023 panic: attempt to unwrap error: UnableToReturnNumber
docgen_tmp/test.zig:9:5: 0x211f7f in getNumberOrFail (test)
return error.UnableToReturnNumber;
^
docgen_tmp/test.zig:4:44: 0x210411 in main (test)
const number = getNumberOrFail() catch unreachable;
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f95c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f461 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
One way to avoid this crash is to test for an error instead of assuming a successful result, with the if
expression:
test.zig
const print = @import("std").debug.print;
pub fn main() void {
const result = getNumberOrFail();
if (result) |number| {
print("got number: {}\n", .{number});
} else |err| {
print("got error: {s}\n", .{@errorName(err)});
}
}
fn getNumberOrFail() !i32 {
return error.UnableToReturnNumber;
}
Shell
$ zig build-exe test.zig
$ ./test
got error: UnableToReturnNumber
See also:
Invalid Error Code
At compile-time:
test.zig
comptime {
const err = error.AnError;
const number = @errorToInt(err) + 10;
const invalid_err = @intToError(number);
_ = invalid_err;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:4:37: error: integer value '11' represents no error
const invalid_err = @intToError(number);
^~~~~~
At runtime:
test.zig
const std = @import("std");
pub fn main() void {
var err = error.AnError;
var number = @errorToInt(err) + 500;
var invalid_err = @intToError(number);
std.debug.print("value: {}\n", .{invalid_err});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3586118 panic: invalid error code
docgen_tmp/test.zig:6:5: 0x2102ca in main (test)
var invalid_err = @intToError(number);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f80c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f311 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Invalid Enum Cast
At compile-time:
test.zig
const Foo = enum {
a,
b,
c,
};
comptime {
const a: u2 = 3;
const b = @intToEnum(Foo, a);
_ = b;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:8:15: error: enum 'test.Foo' has no tag with value '3'
const b = @intToEnum(Foo, a);
^~~~~~~~~~~~~~~~~~
docgen_tmp/test.zig:1:13: note: enum declared here
const Foo = enum {
^~~~
At runtime:
test.zig
const std = @import("std");
const Foo = enum {
a,
b,
c,
};
pub fn main() void {
var a: u2 = 3;
var b = @intToEnum(Foo, a);
std.debug.print("value: {s}\n", .{@tagName(b)});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3586228 panic: invalid enum value
docgen_tmp/test.zig:11:13: 0x210303 in main (test)
var b = @intToEnum(Foo, a);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f85c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f361 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Invalid Error Set Cast
At compile-time:
test.zig
const Set1 = error{
A,
B,
};
const Set2 = error{
A,
C,
};
comptime {
_ = @errSetCast(Set2, Set1.B);
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:10:9: error: 'error.B' not a member of error set 'error{A,C}'
_ = @errSetCast(Set2, Set1.B);
^~~~~~~~~~~~~~~~~~~~~~~~~
docgen_tmp/test.zig:5:14: note: error set declared here
const Set2 = error{
^~~~~
At runtime:
test.zig
const std = @import("std");
const Set1 = error{
A,
B,
};
const Set2 = error{
A,
C,
};
pub fn main() void {
foo(Set1.B);
}
fn foo(set1: Set1) void {
const x = @errSetCast(Set2, set1);
std.debug.print("value: {}\n", .{x});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3586325 panic: invalid error code
docgen_tmp/test.zig:15:15: 0x211e31 in foo (test)
const x = @errSetCast(Set2, set1);
^
docgen_tmp/test.zig:12:13: 0x21029d in main (test)
foo(Set1.B);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f82c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f331 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Incorrect Pointer Alignment
At compile-time:
test.zig
comptime {
const ptr = @intToPtr(*align(1) i32, 0x1);
const aligned = @alignCast(4, ptr);
_ = aligned;
}
Shell
$ zig test test.zig
docgen_tmp/test.zig:3:35: error: pointer address 0x1 is not aligned to 4 bytes
const aligned = @alignCast(4, ptr);
^~~
At runtime:
test.zig
const mem = @import("std").mem;
pub fn main() !void {
var array align(4) = [_]u32{ 0x11111111, 0x11111111 };
const bytes = mem.sliceAsBytes(array[0..]);
if (foo(bytes) != 0x11111111) return error.Wrong;
}
fn foo(bytes: []u8) u32 {
const slice4 = bytes[1..5];
const int_slice = mem.bytesAsSlice(u32, @alignCast(4, slice4));
return int_slice[0];
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3586365 panic: incorrect alignment
docgen_tmp/test.zig:9:39: 0x20fecb in foo (test)
const int_slice = mem.bytesAsSlice(u32, @alignCast(4, slice4));
^
docgen_tmp/test.zig:5:12: 0x20fdff in main (test)
if (foo(bytes) != 0x11111111) return error.Wrong;
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:614:37: 0x20f875 in posixCallMainAndExit (test)
const result = root.main() catch |err| {
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f331 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
Wrong Union Field Access
At compile-time:
test.zig
comptime {
var f = Foo{ .int = 42 };
f.float = 12.34;
}
const Foo = union {
float: f32,
int: u32,
};
Shell
$ zig test test.zig
docgen_tmp/test.zig:3:6: error: access of union field 'float' while field 'int' is active
f.float = 12.34;
~^~~~~~
docgen_tmp/test.zig:6:13: note: union declared here
const Foo = union {
^~~~~
At runtime:
test.zig
const std = @import("std");
const Foo = union {
float: f32,
int: u32,
};
pub fn main() void {
var f = Foo{ .int = 42 };
bar(&f);
}
fn bar(f: *Foo) void {
f.float = 12.34;
std.debug.print("value: {}\n", .{f.float});
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3586461 panic: access of inactive union field
docgen_tmp/test.zig:14:6: 0x227a38 in bar (test)
f.float = 12.34;
^
docgen_tmp/test.zig:10:8: 0x225eac in main (test)
bar(&f);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x22542c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x224f31 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)
This safety is not available for extern
or packed
unions.
To change the active field of a union, assign the entire union, like this:
test.zig
const std = @import("std");
const Foo = union {
float: f32,
int: u32,
};
pub fn main() void {
var f = Foo{ .int = 42 };
bar(&f);
}
fn bar(f: *Foo) void {
f.* = Foo{ .float = 12.34 };
std.debug.print("value: {}\n", .{f.float});
}
Shell
$ zig build-exe test.zig
$ ./test
value: 1.23400001e+01
To change the active field of a union when a meaningful value for the field is not known, use undefined, like this:
test.zig
const std = @import("std");
const Foo = union {
float: f32,
int: u32,
};
pub fn main() void {
var f = Foo{ .int = 42 };
f = Foo{ .float = undefined };
bar(&f);
std.debug.print("value: {}\n", .{f.float});
}
fn bar(f: *Foo) void {
f.float = 12.34;
}
Shell
$ zig build-exe test.zig
$ ./test
value: 1.23400001e+01
See also:
Out of Bounds Float to Integer Cast
TODO
Pointer Cast Invalid Null
This happens when casting a pointer with the address 0 to a pointer which may not have the address 0. For example, C Pointers, Optional Pointers, and allowzero pointers allow address zero, but normal Pointers do not.
At compile-time:
test.zig
comptime {
const opt_ptr: ?*i32 = null;
const ptr = @ptrCast(*i32, opt_ptr);
_ = ptr;
}
Shell
$ zig test test.zig -fstage1
./docgen_tmp/test.zig:3:17: error: null pointer casted to type '*i32'
const ptr = @ptrCast(*i32, opt_ptr);
^
At runtime:
test.zig
pub fn main() void {
var opt_ptr: ?*i32 = null;
var ptr = @ptrCast(*i32, opt_ptr);
_ = ptr;
}
Shell
$ zig build-exe test.zig
$ ./test
thread 3586695 panic: cast causes pointer to be null
docgen_tmp/test.zig:3:15: 0x2101c1 in main (test)
var ptr = @ptrCast(*i32, opt_ptr);
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x20f71c in posixCallMainAndExit (test)
root.main();
^
/home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x20f221 in _start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
(process terminated by signal)