포인터 캐스트 시 널(Null)이 유효하지 않을 때
포인터 캐스트 시 널(Null)이 유효하지 않을 때
본문
주소가 0인 포인터를, 주소 0을 허용하지 않는 포인터 타입으로 캐스팅하면 이 상황이 벌어져요. 주소 0(즉 널)을 허용하는 쪽은 C Pointers, Optional Pointers, 그리고 allowzero 포인터인데, 일반적인 Pointers는 주소 0을 허용하지 않아요.
컴파일 타임(comptime)에는 이렇게 나타납니다.
// test_comptime_invalid_null_pointer_cast.zig
comptime {
const opt_ptr: ?*i32 = null;
const ptr: *i32 = @ptrCast(opt_ptr);
_ = ptr;
}
$ zig test test_comptime_invalid_null_pointer_cast.zig
/home/ci/work/zig-bootstrap/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);
^~~~~~~
런타임에는 이렇게 나타납니다.
// runtime_invalid_null_pointer_cast.zig
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 974044 panic: cast causes pointer to be null
/home/ci/work/zig-bootstrap/zig/doc/langref/runtime_invalid_null_pointer_cast.zig:4:23: 0x11e82aa in main (runtime_invalid_null_pointer_cast.zig)
const ptr: *i32 = @ptrCast(opt_ptr);
^
/home/ci/work/zig-bootstrap/out/host/lib/zig/std/start.zig:788:64: 0x11e7bbb in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/ci/work/zig-bootstrap/out/host/lib/zig/std/start.zig:248:5: 0x11e75e1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)