4 ms·
What about array_start <= ptr && ptr < array_end // or `<=` if the upper bound is inclusive Edit: well, for one it may not be thread safe, since it's not
by pygy_ 10y ago
What about
array_start <= ptr && ptr < array_end // or `<=` if the upper bound is inclusive
Edit: well, for one it may not be thread safe, since it's not atomic, but neither is your example AFAIK.
- nightcracker 10y agoYour edit is pretty much irrelevant - it could be applied to literally any example code anywhere. Unless mentioned otherwise you should assume that all variables are thread-local.
- Sacho 10y agoEvaluating that expression is undefined behavior if ptr is outside the +1 bounds of the array. Check out the enumerated defined behavior in the (old C99, working draft) standard - http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf 6.5.8 Relational operators ...and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values... ... If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.
- pygy_ 10y agoWhelp... Is there a non undefined way to do bounds checking in C?
- Sacho 10y agoI'm just a C newbie, so I can't give you a definitive answer. Here's two I came up with: If you know the bounds of the array, then you could enumerate it and check if the pointers to any of its elements are equal to your pointer. Alternatively you could store references to array elements as a structure of a start pointer + offset, and arrays as a pair of start and end pointers. Then checking if a reference points to part of the array would be a two-step operation - check that the starts match and that your offset is within the end - start bounds.
- pjc50 10y agoAvoid maintaining pointers into arrays and instead maintain indices. If you maintain them as unsigned then you only need one range check (although you then have to avoid underflow if you want to stay in the realm of defined behaviour). One of the downsides to C is that K&R and most source code out there will encourage you to do pointer arithmetic freely, but the standard points out all kinds of surprises where it is undefined. So you get technically non-conformant code in widespread use.