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

Andrea Canciani ranma42 at gmail.com
Fri Nov 26 23:47:27 PST 2010


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.
Why didn't we do it in the first place? (To catch more off-by-one errors?)q

Andrea


More information about the cairo mailing list