非法行为
Zig 中许多操作会触发所谓的“非法行为”(IB)。如果编译时检测到非法行为,Zig 会报编译错误并停止。未在编译时捕获的非法行为则分为两类。
某些非法行为具有安全检查:编译器会在可能于运行时发生非法行为的位置插入“安全检查”,判断它是否即将发生。如果是,安全检查“失败”,并触发 panic。
其他非法行为均不进行检查,即编译器无法为其插入安全检查。运行时发生未检查的非法行为时,任何事情都可能发生:通常是某种崩溃,但优化器可以使其导致任意行为,例如调用任意函数或破坏任意数据。这类似于其他语言的“未定义行为”。注意,在编译时求值时,未检查的非法行为仍始终产生编译错误,因为 Zig 编译器在编译时能够执行比运行时更复杂的检查。
多数非法行为具有安全检查。但为便于优化,fast 和 small 优化模式默认关闭安全检查。也可以使用 @setRuntimeSafety 按块启用或关闭安全检查,覆盖当前优化模式的默认设置。关闭安全检查后,原本带安全检查的非法行为,就会和未检查的非法行为一样,触发后可能导致任意行为。
安全检查失败时,Zig 的默认 panic 处理器会输出栈追踪并崩溃,例如:
test "safety check" {
unreachable;
}$ zig test test_illegal_behavior.zig
1/1 test_illegal_behavior.test.safety check...thread 708685 panic: reached unreachable code
/home/andy/src/zig/doc/langref/test_illegal_behavior.zig:2:5: 0x124c57c in test.safety check (test_illegal_behavior.zig)
unreachable;
^
/home/andy/src/zig/lib/compiler/test_runner.zig:295:25: 0x1200951 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/andy/src/zig/lib/compiler/test_runner.zig:74:28: 0x1200132 in main (test_runner.zig)
return mainTerminal(init);
^
/home/andy/src/zig/lib/std/start.zig:789:88: 0x11fc8cf in callMain (std.zig)
if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11fc2b1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
error: the following test command terminated with signal ABRT:
/home/andy/src/zig/.zig-cache/o/23dbacac7654d6d1e8086c9fb8ab2f8f/test --seed=0x3864c26c
执行到不可达代码
编译时:
comptime {
assert(false);
}
fn assert(ok: bool) void {
if (!ok) unreachable; // 断言失败
}$ zig test test_comptime_reaching_unreachable.zig
/home/andy/src/zig/doc/langref/test_comptime_reaching_unreachable.zig:5:14: error: reached unreachable code
if (!ok) unreachable; // assertion failure
^~~~~~~~~~~
/home/andy/src/zig/doc/langref/test_comptime_reaching_unreachable.zig:2:11: note: called at comptime here
assert(false);
~~~~~~^~~~~~~
运行时:
const std = @import("std");
pub fn main() void {
std.debug.assert(false);
}$ zig build-exe runtime_reaching_unreachable.zig
$ ./runtime_reaching_unreachable
thread 700507 panic: reached unreachable code
/home/andy/src/zig/lib/std/debug.zig:442:14: 0x1029e99 in assert (std.zig)
if (!ok) unreachable; // assertion failure
^
/home/andy/src/zig/doc/langref/runtime_reaching_unreachable.zig:4:21: 0x11e18ae in main (runtime_reaching_unreachable.zig)
std.debug.assert(false);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
索引越界
编译时:
comptime {
const array: [5]u8 = "hello".*;
const garbage = array[5];
_ = garbage;
}$ zig test test_comptime_index_out_of_bounds.zig
/home/andy/src/zig/doc/langref/test_comptime_index_out_of_bounds.zig:3:27: error: index 5 outside array of length 5
const garbage = array[5];
^
运行时:
pub fn main() void {
const x = foo("hello");
_ = x;
}
fn foo(x: []const u8) u8 {
return x[5];
}$ zig build-exe runtime_index_out_of_bounds.zig
$ ./runtime_index_out_of_bounds
thread 702489 panic: index out of bounds: index 5, len 5
/home/andy/src/zig/doc/langref/runtime_index_out_of_bounds.zig:7:13: 0x11e198e in foo (runtime_index_out_of_bounds.zig)
return x[5];
^
/home/andy/src/zig/doc/langref/runtime_index_out_of_bounds.zig:2:18: 0x11e18ba in main (runtime_index_out_of_bounds.zig)
const x = foo("hello");
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
将负数转换为无符号整数
编译时:
comptime {
const value: i32 = -1;
const unsigned: u32 = @intCast(value);
_ = unsigned;
}$ zig test test_comptime_invalid_cast.zig
/home/andy/src/zig/doc/langref/test_comptime_invalid_cast.zig:3:36: error: type 'u32' cannot represent integer value '-1'
const unsigned: u32 = @intCast(value);
^~~~~
运行时:
const std = @import("std");
pub fn main() void {
var value: i32 = -1; // 运行时已知
_ = &value;
const unsigned: u32 = @intCast(value);
std.debug.print("value: {}\n", .{unsigned});
}$ zig build-exe runtime_invalid_cast.zig
$ ./runtime_invalid_cast
thread 699147 panic: integer does not fit in destination type
/home/andy/src/zig/doc/langref/runtime_invalid_cast.zig:6:27: 0x11e18bf in main (runtime_invalid_cast.zig)
const unsigned: u32 = @intCast(value);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
获取无符号整数的最大值,使用 std.math.maxInt。
类型转换截断数据
编译时:
comptime {
const spartan_count: u16 = 300;
const byte: u8 = @intCast(spartan_count);
_ = byte;
}$ zig test test_comptime_invalid_cast_truncate.zig
/home/andy/src/zig/doc/langref/test_comptime_invalid_cast_truncate.zig:3:31: error: type 'u8' cannot represent integer value '300'
const byte: u8 = @intCast(spartan_count);
^~~~~~~~~~~~~
运行时:
const std = @import("std");
pub fn main() void {
var spartan_count: u16 = 300; // 运行时已知
_ = &spartan_count;
const byte: u8 = @intCast(spartan_count);
std.debug.print("value: {}\n", .{byte});
}$ zig build-exe runtime_invalid_cast_truncate.zig
$ ./runtime_invalid_cast_truncate
thread 700509 panic: integer does not fit in destination type
/home/andy/src/zig/doc/langref/runtime_invalid_cast_truncate.zig:6:22: 0x11e18c0 in main (runtime_invalid_cast_truncate.zig)
const byte: u8 = @intCast(spartan_count);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
截断位时,使用 @truncate。
整数溢出
默认运算
以下运算符可能导致整数溢出:
编译时加法示例:
comptime {
var byte: u8 = 255;
byte += 1;
}$ zig test test_comptime_overflow.zig
/home/andy/src/zig/doc/langref/test_comptime_overflow.zig:3:10: error: overflow of integer type 'u8' with value '256'
byte += 1;
~~~~~^~~~
运行时:
const std = @import("std");
pub fn main() void {
var byte: u8 = 255;
byte += 1;
std.debug.print("value: {}\n", .{byte});
}$ zig build-exe runtime_overflow.zig
$ ./runtime_overflow
thread 699141 panic: integer overflow
/home/andy/src/zig/doc/langref/runtime_overflow.zig:5:10: 0x11e18d5 in main (runtime_overflow.zig)
byte += 1;
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
标准库数学函数
标准库提供的这些函数可能返回错误。
@import("std").math.add@import("std").math.sub@import("std").math.mul@import("std").math.divTrunc@import("std").math.divFloor@import("std").math.divCeil@import("std").math.divExact@import("std").math.shl
捕获加法溢出的示例:
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});
}$ zig build-exe math_add.zig
$ ./math_add
unable to add one: Overflow
error: Overflow
/home/andy/src/zig/lib/std/math.zig:571:21: 0x11449b4 in add__func_527 (std.zig)
if (ov[1] != 0) return error.Overflow;
^
/home/andy/src/zig/doc/langref/math_add.zig:8:9: 0x11e0ccf in main (math_add.zig)
return err;
^
内置溢出函数
这些内置函数返回元组,其中包含是否溢出的标记(类型为 u1)以及可能已经溢出的运算结果位:
@addWithOverflow 示例:
const print = @import("std").debug.print;
pub fn main() void {
const byte: u8 = 255;
const ov = @addWithOverflow(byte, 10);
if (ov[1] != 0) {
print("overflowed result: {}\n", .{ov[0]});
} else {
print("result: {}\n", .{ov[0]});
}
}$ zig build-exe addWithOverflow_builtin.zig
$ ./addWithOverflow_builtin
overflowed result: 9
回绕运算
这些操作保证采用回绕语义。
+%(回绕加法)-%(回绕减法)-%(回绕取负)*%(回绕乘法)
const std = @import("std");
const expectEqual = std.testing.expectEqual;
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 expectEqual(minInt(i32), min_val);
const max_val = min_val -% 1;
try expectEqual(maxInt(i32), max_val);
}$ zig test test_wraparound_semantics.zig
1/1 test_wraparound_semantics.test.wraparound addition and subtraction...OK
All 1 tests passed.
精确左移溢出
编译时:
comptime {
const x = @shlExact(@as(u8, 0b01010101), 2);
_ = x;
}$ zig test test_comptime_shlExact_overflow.zig
/home/andy/src/zig/doc/langref/test_comptime_shlExact_overflow.zig:2:15: error: overflow of integer type 'u8' with value '340'
const x = @shlExact(@as(u8, 0b01010101), 2);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
运行时:
const std = @import("std");
pub fn main() void {
var x: u8 = 0b01010101; // 运行时已知
_ = &x;
const y = @shlExact(x, 2);
std.debug.print("value: {}\n", .{y});
}$ zig build-exe runtime_shlExact_overflow.zig
$ ./runtime_shlExact_overflow
thread 707035 panic: left shift overflowed bits
/home/andy/src/zig/doc/langref/runtime_shlExact_overflow.zig:6:5: 0x11e18e1 in main (runtime_shlExact_overflow.zig)
const y = @shlExact(x, 2);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
精确右移溢出
编译时:
comptime {
const x = @shrExact(@as(u8, 0b10101010), 2);
_ = x;
}$ zig test test_comptime_shrExact_overflow.zig
/home/andy/src/zig/doc/langref/test_comptime_shrExact_overflow.zig:2:15: error: exact shift shifted out 1 bits
const x = @shrExact(@as(u8, 0b10101010), 2);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
运行时:
const builtin = @import("builtin");
const std = @import("std");
pub fn main() void {
var x: u8 = 0b10101010; // 运行时已知
_ = &x;
const y = @shrExact(x, 2);
std.debug.print("value: {}\n", .{y});
if ((builtin.cpu.arch.isPowerPC() or builtin.cpu.arch.isRISCV() or builtin.cpu.arch.isLoongArch() or builtin.cpu.arch == .s390x) and builtin.zig_backend == .stage2_llvm) @panic("https://github.com/ziglang/zig/issues/24304");
}$ zig build-exe runtime_shrExact_overflow.zig
$ ./runtime_shrExact_overflow
thread 702495 panic: right shift overflowed bits
/home/andy/src/zig/doc/langref/runtime_shrExact_overflow.zig:7:5: 0x11e18ca in main (runtime_shrExact_overflow.zig)
const y = @shrExact(x, 2);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
除数为零
编译时:
comptime {
const a: i32 = 1;
const b: i32 = 0;
const c = a / b;
_ = c;
}$ zig test test_comptime_division_by_zero.zig
/home/andy/src/zig/doc/langref/test_comptime_division_by_zero.zig:4:19: error: division by zero here causes illegal behavior
const c = a / b;
^
运行时:
const std = @import("std");
pub fn main() void {
var a: u32 = 1;
var b: u32 = 0;
_ = .{ &a, &b };
const c = a / b;
std.debug.print("value: {}\n", .{c});
}$ zig build-exe runtime_division_by_zero.zig
$ ./runtime_division_by_zero
thread 704968 panic: division by zero
/home/andy/src/zig/doc/langref/runtime_division_by_zero.zig:7:17: 0x11e18d0 in main (runtime_division_by_zero.zig)
const c = a / b;
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
取余除数为零
编译时:
comptime {
const a: i32 = 10;
const b: i32 = 0;
const c = a % b;
_ = c;
}$ zig test test_comptime_remainder_division_by_zero.zig
/home/andy/src/zig/doc/langref/test_comptime_remainder_division_by_zero.zig:4:19: error: division by zero here causes illegal behavior
const c = a % b;
^
运行时:
const std = @import("std");
pub fn main() void {
var a: u32 = 10;
var b: u32 = 0;
_ = .{ &a, &b };
const c = a % b;
std.debug.print("value: {}\n", .{c});
}$ zig build-exe runtime_remainder_division_by_zero.zig
$ ./runtime_remainder_division_by_zero
thread 699145 panic: division by zero
/home/andy/src/zig/doc/langref/runtime_remainder_division_by_zero.zig:7:17: 0x11e18d0 in main (runtime_remainder_division_by_zero.zig)
const c = a % b;
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
精确除法存在余数
编译时:
comptime {
const a: u32 = 10;
const b: u32 = 3;
const c = @divExact(a, b);
_ = c;
}$ zig test test_comptime_divExact_remainder.zig
/home/andy/src/zig/doc/langref/test_comptime_divExact_remainder.zig:4:15: error: exact division produced remainder
const c = @divExact(a, b);
^~~~~~~~~~~~~~~
运行时:
const std = @import("std");
pub fn main() void {
var a: u32 = 10;
var b: u32 = 3;
_ = .{ &a, &b };
const c = @divExact(a, b);
std.debug.print("value: {}\n", .{c});
}$ zig build-exe runtime_divExact_remainder.zig
$ ./runtime_divExact_remainder
thread 705407 panic: exact division produced remainder
/home/andy/src/zig/doc/langref/runtime_divExact_remainder.zig:7:15: 0x11e1905 in main (runtime_divExact_remainder.zig)
const c = @divExact(a, b);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
尝试解包空值
编译时:
comptime {
const optional_number: ?i32 = null;
const number = optional_number.?;
_ = number;
}$ zig test test_comptime_unwrap_null.zig
/home/andy/src/zig/doc/langref/test_comptime_unwrap_null.zig:3:35: error: unable to unwrap null
const number = optional_number.?;
~~~~~~~~~~~~~~~^~
运行时:
const std = @import("std");
pub fn main() void {
var optional_number: ?i32 = null;
_ = &optional_number;
const number = optional_number.?;
std.debug.print("value: {}\n", .{number});
}$ zig build-exe runtime_unwrap_null.zig
$ ./runtime_unwrap_null
thread 708134 panic: attempt to use null value
/home/andy/src/zig/doc/langref/runtime_unwrap_null.zig:6:35: 0x11e18d4 in main (runtime_unwrap_null.zig)
const number = optional_number.?;
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
避免此崩溃的一种方式是通过 if 表达式检查空值,而非直接假设非空:
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", .{});
}
}$ zig build-exe testing_null_with_if.zig
$ ./testing_null_with_if
it's null
另见:
尝试解包错误
编译时:
comptime {
const number = getNumberOrFail() catch unreachable;
_ = number;
}
fn getNumberOrFail() !i32 {
return error.UnableToReturnNumber;
}$ zig test test_comptime_unwrap_error.zig
/home/andy/src/zig/doc/langref/test_comptime_unwrap_error.zig:2:44: error: caught unexpected error 'UnableToReturnNumber'
const number = getNumberOrFail() catch unreachable;
^~~~~~~~~~~
/home/andy/src/zig/doc/langref/test_comptime_unwrap_error.zig:7:18: note: error returned here
return error.UnableToReturnNumber;
^~~~~~~~~~~~~~~~~~~~
运行时:
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;
}$ zig build-exe runtime_unwrap_error.zig
$ ./runtime_unwrap_error
thread 706295 panic: attempt to unwrap error: UnableToReturnNumber
error return context:
/home/andy/src/zig/doc/langref/runtime_unwrap_error.zig:9:5: 0x11e18ac in getNumberOrFail (runtime_unwrap_error.zig)
return error.UnableToReturnNumber;
^
stack trace:
/home/andy/src/zig/doc/langref/runtime_unwrap_error.zig:4:44: 0x11e1913 in main (runtime_unwrap_error.zig)
const number = getNumberOrFail() catch unreachable;
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
避免此崩溃的一种方式是通过 if 表达式检查错误,而非直接假设成功:
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;
}$ zig build-exe testing_error_with_if.zig
$ ./testing_error_with_if
got error: UnableToReturnNumber
另见:
无效错误码
编译时:
comptime {
_ = @errorFromInt(12345);
}$ zig test test_comptime_invalid_error_code.zig
/home/andy/src/zig/doc/langref/test_comptime_invalid_error_code.zig:2:23: error: integer value '12345' represents no error
_ = @errorFromInt(12345);
^~~~~
运行时:
const std = @import("std");
pub fn main() void {
const err = error.AnError;
var number = @intFromError(err) + 500;
_ = &number;
const invalid_err = @errorFromInt(number);
std.debug.print("value: {}\n", .{invalid_err});
}$ zig build-exe runtime_invalid_error_code.zig
$ ./runtime_invalid_error_code
thread 701025 panic: invalid error code
/home/andy/src/zig/doc/langref/runtime_invalid_error_code.zig:7:5: 0x11e18e5 in main (runtime_invalid_error_code.zig)
const invalid_err = @errorFromInt(number);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
无效枚举转换
编译时:
const Foo = enum(u2) {
a,
b,
c,
};
comptime {
const a: u2 = 3;
const b: Foo = @fromBackingInt(a);
_ = b;
}$ zig test test_comptime_invalid_enum_cast.zig
/home/andy/src/zig/doc/langref/test_comptime_invalid_enum_cast.zig:8:20: error: enum 'test_comptime_invalid_enum_cast.Foo' has no tag with value '3'
const b: Foo = @fromBackingInt(a);
^~~~~~~~~~~~~~~~~~
/home/andy/src/zig/doc/langref/test_comptime_invalid_enum_cast.zig:1:13: note: enum declared here
const Foo = enum(u2) {
^~~~
运行时:
const std = @import("std");
const Foo = enum(u2) {
a,
b,
c,
};
fn foo(a: u2) void {
const b: Foo = @fromBackingInt(a);
std.debug.print("value: {s}\n", .{@tagName(b)});
}
pub fn main() void {
foo(3);
}$ zig build-exe runtime_invalid_enum_cast.zig
$ ./runtime_invalid_enum_cast
thread 705398 panic: invalid enum value
/home/andy/src/zig/doc/langref/runtime_invalid_enum_cast.zig:10:20: 0x11e19bb in foo (runtime_invalid_enum_cast.zig)
const b: Foo = @fromBackingInt(a);
^
/home/andy/src/zig/doc/langref/runtime_invalid_enum_cast.zig:15:8: 0x11e18ae in main (runtime_invalid_enum_cast.zig)
foo(3);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
无效错误集合转换
编译时:
const Set1 = error{
A,
B,
};
const Set2 = error{
A,
C,
};
comptime {
_ = @as(Set2, @errorCast(Set1.B));
}$ zig test test_comptime_invalid_error_set_cast.zig
/home/andy/src/zig/doc/langref/test_comptime_invalid_error_set_cast.zig:10:19: error: 'error.B' not a member of error set 'error{A,C}'
_ = @as(Set2, @errorCast(Set1.B));
^~~~~~~~~~~~~~~~~~
运行时:
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: Set2 = @errorCast(set1);
std.debug.print("value: {}\n", .{x});
}$ zig build-exe runtime_invalid_error_set_cast.zig
$ ./runtime_invalid_error_set_cast
thread 703127 panic: unexpected error code, found error.B
/home/andy/src/zig/doc/langref/runtime_invalid_error_set_cast.zig:15:21: 0x11e19b1 in foo (runtime_invalid_error_set_cast.zig)
const x: Set2 = @errorCast(set1);
^
/home/andy/src/zig/doc/langref/runtime_invalid_error_set_cast.zig:12:8: 0x11e18b7 in main (runtime_invalid_error_set_cast.zig)
foo(Set1.B);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
指针对齐不正确
编译时:
comptime {
const ptr: *align(1) i32 = @ptrFromInt(0x1);
const aligned: *align(4) i32 = @alignCast(ptr);
_ = aligned;
}$ zig test test_comptime_incorrect_pointer_alignment.zig
/home/andy/src/zig/doc/langref/test_comptime_incorrect_pointer_alignment.zig:3:47: error: pointer address 0x1 is not aligned to 4 bytes
const aligned: *align(4) i32 = @alignCast(ptr);
^~~
运行时:
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, @as([]align(4) u8, @alignCast(slice4)));
return int_slice[0];
}$ zig build-exe runtime_incorrect_pointer_alignment.zig
$ ./runtime_incorrect_pointer_alignment
thread 701026 panic: incorrect alignment
/home/andy/src/zig/doc/langref/runtime_incorrect_pointer_alignment.zig:9:64: 0x11e2296 in foo (runtime_incorrect_pointer_alignment.zig)
const int_slice = mem.bytesAsSlice(u32, @as([]align(4) u8, @alignCast(slice4)));
^
/home/andy/src/zig/doc/langref/runtime_incorrect_pointer_alignment.zig:5:12: 0x11e0c6e in main (runtime_incorrect_pointer_alignment.zig)
if (foo(bytes) != 0x11111111) return error.Wrong;
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e1286 in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
访问错误的联合字段
编译时:
comptime {
var f = Foo{ .int = 42 };
f.float = 12.34;
}
const Foo = union {
float: f32,
int: u32,
};$ zig test test_comptime_wrong_union_field_access.zig
/home/andy/src/zig/doc/langref/test_comptime_wrong_union_field_access.zig:3:6: error: access of union field 'float' while field 'int' is active
f.float = 12.34;
~^~~~~~
/home/andy/src/zig/doc/langref/test_comptime_wrong_union_field_access.zig:6:13: note: union declared here
const Foo = union {
^~~~~
运行时:
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});
}$ zig build-exe runtime_wrong_union_field_access.zig
$ ./runtime_wrong_union_field_access
thread 702510 panic: access of union field 'float' while field 'int' is active
/home/andy/src/zig/doc/langref/runtime_wrong_union_field_access.zig:14:6: 0x11e197e in bar (runtime_wrong_union_field_access.zig)
f.float = 12.34;
^
/home/andy/src/zig/doc/langref/runtime_wrong_union_field_access.zig:10:8: 0x11e18be in main (runtime_wrong_union_field_access.zig)
bar(&f);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
此项安全检查不适用于 extern 或 packed 联合。
要改变联合的活动字段,需对整个联合赋值,例如:
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});
}$ zig build-exe change_active_union_field.zig
$ ./change_active_union_field
value: 12.34
如果需要改变联合的活动字段,但不知道字段的有效值,可以使用 undefined,例如:
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;
}$ zig build-exe undefined_active_union_field.zig
$ ./undefined_active_union_field
value: 12.34
另见:
浮点数转整数越界
当浮点值超出目标整数类型范围,却尝试将其转换为该整数类型时,会发生此错误。
编译时:
comptime {
const float: f32 = 4294967296;
const int: i32 = @intFromFloat(float);
_ = int;
}$ zig test test_comptime_out_of_bounds_float_to_integer_cast.zig
/home/andy/src/zig/doc/langref/test_comptime_out_of_bounds_float_to_integer_cast.zig:3:36: error: float value '4294967296' cannot be stored in integer type 'i32'
const int: i32 = @intFromFloat(float);
^~~~~
运行时:
pub fn main() void {
var float: f32 = 4294967296; // 运行时已知
_ = &float;
const int: i32 = @intFromFloat(float);
_ = int;
}$ zig build-exe runtime_out_of_bounds_float_to_integer_cast.zig
$ ./runtime_out_of_bounds_float_to_integer_cast
thread 708097 panic: integer part of floating point value out of bounds
/home/andy/src/zig/doc/langref/runtime_out_of_bounds_float_to_integer_cast.zig:4:22: 0x11e18ee in main (runtime_out_of_bounds_float_to_integer_cast.zig)
const int: i32 = @intFromFloat(float);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
指针转换产生无效空值
将零地址指针转换为不允许零地址的指针时,会发生此错误。例如,C 指针、可选指针和 allowzero 指针允许零地址,普通指针则不允许。
编译时:
comptime {
const opt_ptr: ?*i32 = null;
const ptr: *i32 = @ptrCast(opt_ptr);
_ = ptr;
}$ zig test test_comptime_invalid_null_pointer_cast.zig
/home/andy/src/zig/doc/langref/test_comptime_invalid_null_pointer_cast.zig:3:32: error: null pointer casted to type '*i32'
const ptr: *i32 = @ptrCast(opt_ptr);
^~~~~~~
运行时:
pub fn main() void {
var opt_ptr: ?*i32 = null;
_ = &opt_ptr;
const ptr: *i32 = @ptrCast(opt_ptr);
_ = ptr;
}$ zig build-exe runtime_invalid_null_pointer_cast.zig
$ ./runtime_invalid_null_pointer_cast
thread 707068 panic: cast causes pointer to be null
/home/andy/src/zig/doc/langref/runtime_invalid_null_pointer_cast.zig:4:23: 0x11e18ca in main (runtime_invalid_null_pointer_cast.zig)
const ptr: *i32 = @ptrCast(opt_ptr);
^
/home/andy/src/zig/lib/std/start.zig:788:64: 0x11e11db in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11e0c11 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)