[Date Prev][Date Next] [Chronological] [Thread] [Top]

Re: commit: ldap/servers/slapd/back-ldbm attr.c



> Pierangelo Masarati writes:
>> #if SAFE
>> #define PTRCMP(x,y) ((x) - (y))
>> #else
>> #define PTRCMP(x,y) ((x) > (y) ? 1 : ((x) < (y) ? -1 : 0)
>
>   #define PTRCMP(x,y) ((x) < (y) ? -1 : (x) > (y))
>
> is slightly briefer and might give shorter code.

I'm not sure we can rely on (x) > (y) returning 1 if true.
I vaguely recall reading that this is much implementation
dependent, one can only rely on 0 being false and anything
else being true.

>
>> #endif
>>
>> where SAFE is: ptrdiff_t is:
>>   - declared
>
> OK,
>
>>   - large enough to contain +/- the space addressable
>>     by our pointers
>
> How do you test that?  Keep malloc()ing until it fails, and compare the
> resulting pointers as well as some pointers to static memory?

At configure time, forcing pointers by means of integers.
e.g.:

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <malloc.h>
#include <assert.h>

int
main(void)
{
        void *x = 0x0;
        unsigned long long i;

        for (i = 1; i <= ULONG_MAX; (i <<= 1) ) {
                void            *y = (void *)i;
                ptrdiff_t       dplus = y - x, dminus = x - y;
                int             castd;

                printf("%llu\n", i);
                assert( y > x ) ;
                assert( dplus > 0 );
                assert( dminus < 0 );

                castd = (int)dplus;
                assert( castd > 0 );

                castd = (int)dminus;
                assert( castd < 0 );
        }

        return 0;
}

on my system this fails when trying to use i = 2147483648
which is 1 more than MAX_INT.  If we can restrict the
addressable space, e.g. by knowning all the memory comes
from one malloc, then it's fine (what about if comparing
with NULL ?).

>
>>   - its cast to int (since AVL cmp funcs return int)
>>     doesn't lose the sign bit
>
> How do you test that?  Remember that integers may have padding bits, so
> you can't just test sizeof(int) and sizeof(ptrdiff_t).  Do we simply
> assume that an implementation is not so crazy as to have the same size
> of the two, but padding bits in int and not in ptrdiff_t?

See above.  On my system ptrdiff_t corresponds to int
so if the above mentioned assumptions are valid, it
would be safe; on others, it may not.

>
>> Of course, we may simply stay with !SAFE;
>> we'd basically waste one comparison ...
>
> That has my vote.  Unless profiling shows that these functions are
> called frequently enough to take some time, which I doubt.  But if you
> wish, go ahead.  For profiling, you might use
>
> int PTRCMP(const void *x, const void *y)
> {
>     return x < y ? -1 : x > y;
> }

with a test

assert( ( x > y ) > 0 );

:) Ando.

-- 
Pierangelo Masarati
mailto:pierangelo.masarati@sys-net.it