[cairo] [cairo-commit] 3 commits - src/cairo-array.c src/cairoint.h src/cairo-types-private.h

Behdad Esfahbod behdad at behdad.org
Sat Nov 27 14:20:12 PST 2010


On 11/27/10 02:47, Andrea Canciani wrote:
> On Sat, Nov 27, 2010 at 2:03 AM, Behdad Esfahbod <behdad at behdad.org> wrote:
>> On 11/24/10 08:47, Andrea Canciani wrote:
>>> +const void *
>>> +_cairo_array_index_const (const cairo_array_t *array, unsigned int index)
>>> +{
>>> +    /* We allow an index of 0 for the no-elements case.
>>> +     * This makes for cleaner calling code which will often look like:
>>> +     *
>>> +     *    elements = _cairo_array_index_const (array, num_elements);
>>> +     *         for (i=0; i < num_elements; i++) {
>>> +     *        ... read elements[i] here ...
>>> +     *    }
>>> +     *
>>> +     * which in the num_elements==0 case gets the NULL pointer here,
>>> +     * but never dereferences it.
>>> +     */
>>> +    if (index == 0 && array->num_elements == 0)
>>> +     return NULL;
>>> +
>>> +    assert (index < array->num_elements);
>>> +
>>> +    return array->elements + index * array->element_size;
>>> +}
>>
>> Actually the C standard allows for getting the address of the element right
>> after the end of an array.  That's a very legitimate use, for example to
>> compute an "end" pointer to which you'll compare your iterator in a loop.  The
>> element 0 of an empty array is just a special case of that.  May want to allow
>> it here as well.
> 
> _cairo_array_index_const is the "const" counterpart of _cairo_array_index.
> If we decide that we want to allow the post-last element, we probably want to do
> it for both functions.

But the end item ought to be const ;).

> Why didn't we do it in the first place? (To catch more off-by-one errors?)q

Quite possibly.  Maybe it's a good idea to keep it there then.  If we need the
last element, we can always add another function.

Sorry for the noise,
b

> Andrea
> 


More information about the cairo mailing list