#Why does taking a zero-length slice of a null pointer produce a NPE?

1 messages · Page 1 of 1 (latest)

toxic cypress
#

I have some code that's dealing with a C library, which has some data structure with some_array and some_array_count fields. I would really like to do this:

for (data.some_array[0..data.some_array_count]) |item| {
    ...
}

But when the array has zero length, the C library will fill it in with a null pointer, and Zig gives me a NPE in debug mode upon trying to iterate through the zero-length "slice" here even though the for loop should just do nothing. Does anyone know what the language rationale behind this decision was/the broader language context? I would love to be able to do this instead of manually indexing which just adds another line of code to do the same thing.

radiant wagon
#

what is data.some_array? is this coming directly from a C structure? if some_array is a [*c] then you should check for null beforehand, slicing a null pointer is invalid, and that's the problem, not that you're iterating, it's that you're slicing

toxic cypress
#

why does the language even let you slice a [*c] at all if slicing a null pointer isn't allowed by the language, shouldn't you have to do data.some_array.?[...] then?

#

at least then it isn't implicit behavior