diff --git a/src/codegen.cpp b/src/codegen.cpp index 87881ccaf..7d3e008a2 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -3869,6 +3869,9 @@ static LLVMValueRef ir_render_elem_ptr(CodeGen *g, IrExecutableGen *executable, assert(array_type->data.pointer.child_type->id == ZigTypeIdArray); array_type = array_type->data.pointer.child_type; } + + assert(array_type->data.array.len != 0 || array_type->data.array.sentinel != nullptr); + if (safety_check_on) { uint64_t extra_len_from_sentinel = (array_type->data.array.sentinel != nullptr) ? 1 : 0; uint64_t full_len = array_type->data.array.len + extra_len_from_sentinel; diff --git a/src/ir.cpp b/src/ir.cpp index 00bd83f95..5c8d8157d 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -21199,6 +21199,11 @@ static IrInstGen *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstSrcElemP } if (array_type->id == ZigTypeIdArray) { + if(array_type->data.array.len == 0 && array_type->data.array.sentinel == nullptr){ + ir_add_error(ira, &elem_ptr_instruction->base.base, buf_sprintf("accessing a zero length array is not allowed")); + return ira->codegen->invalid_inst_gen; + } + ZigType *child_type = array_type->data.array.child_type; if (ptr_type->data.pointer.host_int_bytes == 0) { return_type = get_pointer_to_type_extra(ira->codegen, child_type, diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 22c473e22..d6d3d331e 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -4552,7 +4552,17 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\ const pointer = &array[0]; \\} , &[_][]const u8{ - "tmp.zig:3:27: error: index 0 outside array of size 0", + "tmp.zig:3:27: error: accessing a zero length array is not allowed", + }); + + cases.add("indexing an array of size zero with runtime index", + \\const array = [_]u8{}; + \\export fn foo() void { + \\ var index: usize = 0; + \\ const pointer = &array[index]; + \\} + , &[_][]const u8{ + "tmp.zig:4:27: error: accessing a zero length array is not allowed", }); cases.add("compile time division by zero",