pointer-in-array test

I

Ike Naar

Hi,

Asking your advice on the following subject:

Suppose I want to find out whether a given pointer (say, p) of type *T
points to an element of a given array (say, a) of type T[max].
A way to achieve this would be a linear search through the array:

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=0;
while (j!=max && a+j!=p) ++j;
return j!=max;
}

Obviously, this algorithm is terribly slow for large max.

A more efficient algorithm is

int ptrInArrUnsafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=p-a; /* possibly undefined */
return 0<=j && j<max && a+j==p;
}

If p points to an element of a[max], j will be a valid index and
the return expression will evaluate to true.
If p does not point to an element of a[max], the pointer subtraction may
invoke undefined behaviour; garbage will be stored in j, and at least one
of the conjuncts of the return expression will evaluate to false.

Apart from storing garbage in j, the pointer subtraction could, in theory,
crash the system, re-format the floppy disk or wake up nasal daemons,
but this has not happened so far on any platform with any compiler
(tried several).

My question is, do you experts in this group see any real problem with
the second algorithm? Alternatively, would there be a faster algorithm
than the first one, that does not invoke undefined behaviour?

Thanks in advance,
Ike
 
B

Barry Schwarz

Hi,

Asking your advice on the following subject:

Suppose I want to find out whether a given pointer (say, p) of type *T
points to an element of a given array (say, a) of type T[max].
A way to achieve this would be a linear search through the array:

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=0;
while (j!=max && a+j!=p) ++j;
return j!=max;
}

Obviously, this algorithm is terribly slow for large max.

A more efficient algorithm is

int ptrInArrUnsafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=p-a; /* possibly undefined */
return 0<=j && j<max && a+j==p;
}

If p points to an element of a[max], j will be a valid index and
the return expression will evaluate to true.
If p does not point to an element of a[max], the pointer subtraction may
invoke undefined behaviour; garbage will be stored in j, and at least one
of the conjuncts of the return expression will evaluate to false.

Apart from storing garbage in j, the pointer subtraction could, in theory,
crash the system, re-format the floppy disk or wake up nasal daemons,
but this has not happened so far on any platform with any compiler
(tried several).

My question is, do you experts in this group see any real problem with
the second algorithm? Alternatively, would there be a faster algorithm
than the first one, that does not invoke undefined behaviour?
If your system supports the optional intptr_t type, you can convert p,
a, and a+1 to integers and determine the correct answer without fear
of undefined behavior.


<<Remove the del for email>>
 
C

CBFalconer

Ike said:
Suppose I want to find out whether a given pointer (say, p) of type
*T points to an element of a given array (say, a) of type T[max].
A way to achieve this would be a linear search through the array:

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=0;
while (j!=max && a+j!=p) ++j;
return j!=max;
}

Obviously, this algorithm is terribly slow for large max.

A more efficient algorithm is

int ptrInArrUnsafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=p-a; /* possibly undefined */
return 0<=j && j<max && a+j==p;
}
.... snip ...

My question is, do you experts in this group see any real problem
with the second algorithm? Alternatively, would there be a faster
algorithm than the first one, that does not invoke undefined
behaviour?

This is the sort of thing that you put in a file marked as system
dependant code, and include both versions, controlled by some
define.

However I would look closely at the reason for having such a
routine, and try to avoid it in the first place.

The safe version can possibly be slightly sped up by:

/* check whether p points to an element of a[max] */
int ptrInArrSafe(T *p, const T *a, int max)
{
T *pp;

for (pp = a + max; a < pp; a++)
if (p == a) return 1;
return 0;
}

which treats the valid, but undereferenceable, pointer one past
the end of a (value pp) as not within a. This may or may not be
what you want.
 
B

Bernhard Holzmayer

Ike said:
Suppose I want to find out whether a given pointer (say, p) of
type *T points to an element of a given array (say, a) of type
T[max]. A way to achieve this would be a linear search through the
array:

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=0;
while (j!=max && a+j!=p) ++j;
return j!=max;
}

Sorry Ike,
if it's a naive question.

If you really have an array, why don't you just use a thing like the
following

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
if (p<a) return 0; /*out*/

if (p> &a[max-1]) return 0; /* out */

if ( (p-a) % sizeof(T)) return 0; /* not at element start*/

return 1; /* in and on element start */
}

This should be sufficient, if you want to check only the borders and
that your pointer is at the beginning of an element a[x].

Bernhard
 
M

Martin Dickopp

Barry Schwarz said:
Hi,

Asking your advice on the following subject:

Suppose I want to find out whether a given pointer (say, p) of type *T
points to an element of a given array (say, a) of type T[max].
A way to achieve this would be a linear search through the array:

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=0;
while (j!=max && a+j!=p) ++j;
return j!=max;
}

Obviously, this algorithm is terribly slow for large max.

A more efficient algorithm is

int ptrInArrUnsafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=p-a; /* possibly undefined */
return 0<=j && j<max && a+j==p;
}

If p points to an element of a[max], j will be a valid index and
the return expression will evaluate to true.
If p does not point to an element of a[max], the pointer subtraction may
invoke undefined behaviour; garbage will be stored in j, and at least one
of the conjuncts of the return expression will evaluate to false.

Apart from storing garbage in j, the pointer subtraction could, in theory,
crash the system, re-format the floppy disk or wake up nasal daemons,
but this has not happened so far on any platform with any compiler
(tried several).

My question is, do you experts in this group see any real problem with
the second algorithm? Alternatively, would there be a faster algorithm
than the first one, that does not invoke undefined behaviour?
If your system supports the optional intptr_t type, you can convert p,
a, and a+1 to integers and determine the correct answer without fear
of undefined behavior.

You'd still have to fear implementation-defined behavior, though. :)

There is no guarantee that (intptr_t)(void *)&a[1] is greater than
(intptr_t)(void *)&a[0].

Martin
 
B

Bernhard Holzmayer

Ike said:
Hi Bernard,

: If you really have an array, why don't you just use a thing like
: the following
:
: int ptrInArrSafe(T *p,T *a,int max)
: /* check whether p points to an element of a[max] */
: {
: if (p<a) return 0; /*out*/
: if (p> &a[max-1]) return 0; /* out */
: if ( (p-a) % sizeof(T)) return 0; /* not at element start*/
: return 1; /* in and on element start */
: }
:
: This should be sufficient, if you want to check only the borders
: and that your pointer is at the beginning of an element a[x].

If p does not point to an element of a[max], all comparisons
(p<a), (p>&a[max-1]) and ((p-a)%sizeof(T)) invoke undefined
behaviour and can evaluate to anything, including 'true'.
So your solution may produce a 'false positive' result.

: Bernhard

Sorry,
pardon me for not checking my code intensively enough.
I just checked with a 'gcc -pedantic' which didn't throw an error :(

What about this solution:
int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
long px = (long)p;
long ax = (long)a;
if (px<ax) return 0; /*out*/
if (px> (long)&a[max-1]) return 0; /* out */
if ( (px-ax) % sizeof(T)) return 0; /* not at element start*/
return 1; /* in and on element start */
}

compiles, links, runs without problems with my gcc.
And, as far as I remember, it's legal, to compare pointers after
conversion to long.

Bernhard
 
B

Bernhard Holzmayer

Keith said:
The only guarantee for intptr_t is that you can convert a void* to
intptr_t and back to void*, and the result will compare equal to
the
original void*. It's not clear (to me) that relational operators
are sufficiently well-defined to allow reliably checking whether a
pointer points within an array.

Suppose a char* pointer consists of a word pointer with a byte
offset in the high-order bits, and that pointer-to-integer
pointer-to-integer is not enough.
IMHO you have to use pointer-to-long which must be well-defined
according to the standard, which means, that a long is big enough
to hold a pointer on that system. An integer might be too short.
 
M

Martin Dickopp

Bernhard Holzmayer said:
Ike said:
Suppose I want to find out whether a given pointer (say, p) of
type *T points to an element of a given array (say, a) of type
T[max]. A way to achieve this would be a linear search through the
array:

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=0;
while (j!=max && a+j!=p) ++j;
return j!=max;
}

Sorry Ike,
if it's a naive question.

If you really have an array, why don't you just use a thing like the
following

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
if (p<a) return 0; /*out*/

As is just being discussed in the thread "pointer equality", this
invokes undefined behavior if `p' does not point into `a' (or to the
location just following the last element of `a').
if (p> &a[max-1]) return 0; /* out */

So does this.

Martin
 
I

Ike Naar

Hi Bernard,

: If you really have an array, why don't you just use a thing like the
: following
:
: int ptrInArrSafe(T *p,T *a,int max)
: /* check whether p points to an element of a[max] */
: {
: if (p<a) return 0; /*out*/
: if (p> &a[max-1]) return 0; /* out */
: if ( (p-a) % sizeof(T)) return 0; /* not at element start*/
: return 1; /* in and on element start */
: }
:
: This should be sufficient, if you want to check only the borders and
: that your pointer is at the beginning of an element a[x].

If p does not point to an element of a[max], all comparisons
(p<a), (p>&a[max-1]) and ((p-a)%sizeof(T)) invoke undefined
behaviour and can evaluate to anything, including 'true'.
So your solution may produce a 'false positive' result.

: Bernhard
 
P

pete

Bernhard said:
Ike said:
Suppose I want to find out whether a given pointer (say, p) of
type *T points to an element of a given array (say, a) of type
T[max]. A way to achieve this would be a linear search through the
array:

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=0;
while (j!=max && a+j!=p) ++j;
return j!=max;
}

Sorry Ike,
if it's a naive question.

If you really have an array, why don't you just use a thing like the
following

int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
if (p<a) return 0; /*out*/

if (p> &a[max-1]) return 0; /* out */

if ( (p-a) % sizeof(T)) return 0; /* not at element start*/

return 1; /* in and on element start */
}

(p<a), (p> &a[max-1]), and (p-a), are all undefined
if p and a point to bytes of unrelated objects.
 
I

Ike Naar

: Ike Naar wrote:
:> Suppose I want to find out whether a given pointer (say, p) of type
:> *T points to an element of a given array (say, a) of type T[max].
:> A way to achieve this would be a linear search through the array:
:>
:> int ptrInArrSafe(T *p,T *a,int max)
:> /* check whether p points to an element of a[max] */
:> {
:> int j=0;
:> while (j!=max && a+j!=p) ++j;
:> return j!=max;
:> }
:>
:> Obviously, this algorithm is terribly slow for large max.
:
: The safe version can possibly be slightly sped up by:
:
: /* check whether p points to an element of a[max] */
: int ptrInArrSafe(T *p, const T *a, int max)
: {
: T *pp;
:
: for (pp = a + max; a < pp; a++)
: if (p == a) return 1;
: return 0;
: }
:
: which treats the valid, but undereferenceable, pointer one past
: the end of a (value pp) as not within a. This may or may not be
: what you want.

That's what I want. To be precise, I want to know if there exists an
index j such that 0 <= j < max and &a[j] == p .

But apart from stylistic differences, I see no reason why your
solution would be any faster or slower than mine.
Both algorithms perform a linear search on the array.

: USE worldnet address!
 
K

Keith Thompson

Barry Schwarz said:
If your system supports the optional intptr_t type, you can convert p,
a, and a+1 to integers and determine the correct answer without fear
of undefined behavior.

The only guarantee for intptr_t is that you can convert a void* to
intptr_t and back to void*, and the result will compare equal to the
original void*. It's not clear (to me) that relational operators are
sufficiently well-defined to allow reliably checking whether a pointer
points within an array.

Suppose a char* pointer consists of a word pointer with a byte offset
in the high-order bits, and that pointer-to-integer conversion simply
copies the bits. This satisfies the standard and allows the type
intptr_t to be defined, but doesn't support the kind of comparisons
required. The code (see previous posts) avoids undefined behavior,
but it yields incorrect results.
 
P

pete

Bernhard said:
IMHO you have to use pointer-to-long which must be well-defined
according to the standard, which means, that a long is big enough
to hold a pointer on that system. An integer might be too short.

Whether or not a pointer can be converted to any integer type
is implementation defined.
The standard does not guarantee that relationships which hold
for two pointers, will also hold for their converted integer values.

N869
6.3.2.3 Pointers
[#6] Any pointer type may be converted to an integer type.
Except as previously specified, the result is
implementation-defined. If the result cannot be represented
in the integer type, the behavior is undefined. The result
need not be in the range of values of any integer type.
 
T

Thomas Stegen

Ike said:
Hi,

Asking your advice on the following subject:

Suppose I want to find out whether a given pointer (say, p) of type *T
points to an element of a given array (say, a) of type T[max].
A way to achieve this would be a linear search through the array:

Can you associate with the value of the pointer whether or not it
points into a certain array when it is set? For example in a hashtable
which maps pointers to arrays? This way you can at least amortize the
cost and have a lookup time roundabout O(1).
 
T

Thomas Stegen

Bernhard said:
Sorry,
pardon me for not checking my code intensively enough.
I just checked with a 'gcc -pedantic' which didn't throw an error :(

What about this solution:
int ptrInArrSafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
long px = (long)p;
long ax = (long)a;
if (px<ax) return 0; /*out*/
if (px> (long)&a[max-1]) return 0; /* out */
if ( (px-ax) % sizeof(T)) return 0; /* not at element start*/
return 1; /* in and on element start */
}

The above is valid in that it does not invoke UB. It does however
depend on implementation defined behaviour and so is not guaranteed
to work for all platforms. But it is definetely the way I would do
it. Just have some conditional compilation which does something that
is guaranteed to work if the platform does not support the above.
compiles, links, runs without problems with my gcc.
And, as far as I remember, it's legal, to compare pointers after
conversion to long.

It is legal, but the conversion to long is implementation defined.
And unsigned long might be a better choice.
 
D

Dik T. Winter

> What about this solution:
> int ptrInArrSafe(T *p,T *a,int max)
> /* check whether p points to an element of a[max] */
> {
> long px = (long)p;
> long ax = (long)a;
> if (px<ax) return 0; /*out*/
> if (px> (long)&a[max-1]) return 0; /* out */
> if ( (px-ax) % sizeof(T)) return 0; /* not at element start*/
> return 1; /* in and on element start */
> }
>
> compiles, links, runs without problems with my gcc.
> And, as far as I remember, it's legal, to compare pointers after
> conversion to long.

But the result is implementation defined. I know of at least one
system where it will fail to give the correct answer, then T is char.
For instance:
(long)(a + 7) > (long)(a + 8)
when a is an array of type char.
 
E

Eric Sosman

Ike said:
[...]
A more efficient algorithm is

int ptrInArrUnsafe(T *p,T *a,int max)
/* check whether p points to an element of a[max] */
{
int j=p-a; /* possibly undefined */
return 0<=j && j<max && a+j==p;
}

If p points to an element of a[max], j will be a valid index and
the return expression will evaluate to true.

Agree.
If p does not point to an element of a[max], the pointer subtraction may
invoke undefined behaviour; garbage will be stored in j, and at least one
of the conjuncts of the return expression will evaluate to false.

Disagree. Everything seems correct up to the semicolon,
but after that things fall apart:

- First, it is not necessarily the case that garbage will
be stored in j. "Undefined behavior" is "undefined,"
and does not necessarily result in storing anything at
all anywhere at all.

- Second, even if something does get stored into j, it's
not certain that the "something" will be recognizable
as "garbage." For example, the value zero might be
stored into j, just as if you had called

ptrInArrUnsafe(&array[0], array, 1)

- ... and if this (or something like it) happens, the
return expression will evaluate true, not false.
Apart from storing garbage in j, the pointer subtraction could, in theory,
crash the system, re-format the floppy disk or wake up nasal daemons,
but this has not happened so far on any platform with any compiler
(tried several).

Personally, I've never seen demons fly from my nose (they're
awfully fast, and are usually out of sight before I notice them).
But one need not invoke exotic architectures to get weird behavior
out of violating the rules of pointer subtraction. For example,
consider a "plain vanilla" system with nice linear addressing,
where pointers are just unadorned numeric addresses. Now try
this on for size:

typedef char[8] T;
T array[5];
printf ("%d\n", ptrInArrUnsafe(&array[0][1], array, 5));

It is quite likely (not certain, of course: undefined behavior
is undefined) that j will compute as zero inside the function,
leading the function to conclude that the pointer is valid.
The conclusion is utterly wrong, of course: the pointer aims
not at the start of a T object, but one byte past the start
of the first T object in the array.
My question is, do you experts in this group see any real problem with
the second algorithm?

Yes, as explained above.
Alternatively, would there be a faster algorithm
than the first one, that does not invoke undefined behaviour?

I cannot think of one. As CBF suggests, you should (a)
re-examine whether such a test is required, and if it is
you should (b) isolate the test to a system-dependent source
file, not intended to be portable.
 
C

CBFalconer

Ike said:
.... snip ...

But apart from stylistic differences, I see no reason why your
solution would be any faster or slower than mine.
Both algorithms perform a linear search on the array.

I did say "possibly". It would depend on the optimization
capabilities of the compiler.
 
I

Ike Naar

Hi Eric,

: Ike Naar wrote:
:> int ptrInArrUnsafe(T *p,T *a,int max)
:> /* check whether p points to an element of a[max] */
:> {
:> int j=p-a; /* possibly undefined */
:> return 0<=j && j<max && a+j==p;
:> }
:> [...]
:> If p does not point to an element of a[max], the pointer subtraction may
:> invoke undefined behaviour; garbage will be stored in j, and at least one
:> of the conjuncts of the return expression will evaluate to false.
: Disagree. Everything seems correct up to the semicolon,
: but after that things fall apart:
: - First, it is not necessarily the case that garbage will
: be stored in j. "Undefined behavior" is "undefined,"
: and does not necessarily result in storing anything at
: all anywhere at all.

Of course the implementation is free to do anything it wants after
undefined behaviour, but let's pretend that the damage is limited
to whatever is stored in j. If nothing is stored in j, fine. Perhaps
j retains its old value (whatever that was).

: - Second, even if something does get stored into j, it's
: not certain that the "something" will be recognizable
: as "garbage."

It seems that our notions of "garbage" differ.
My garbage can have any value.

: For example, the value zero might be
: stored into j, just as if you had called
: ptrInArrUnsafe(&array[0], array, 1)
: - ... and if this (or something like it) happens, the
: return expression will evaluate true, not false.

If 0<=j<max, the last conjuct (a+j==p) has to be false, due to the
initial assumption that p was not pointing to an element of a .

Conversely, if the return expression evaluates true there would
have been no undefined behaviour, since in that case there exists
an index j such that 0<=j<max and &a[j]==p (that's what the return
expression implies), i.e. p points to an element of a, and
the pointer subtraction (p-a) would have been OK.

:> [...]
: But one need not invoke exotic architectures to get weird behavior
: out of violating the rules of pointer subtraction. For example,
: consider a "plain vanilla" system with nice linear addressing,
: where pointers are just unadorned numeric addresses. Now try
: this on for size:

: typedef char[8] T;

<nitpicking -- this is C.L.C. after all, isn't it?>
typedef char T[8];
</nitpicking>

: T array[5];
: printf ("%d\n", ptrInArrUnsafe(&array[0][1], array, 5));

This is an extra complication that does not apply to the original problem
where p is supposed to have type T* . &array[0][1] is not a T* .

: It is quite likely (not certain, of course: undefined behavior
: is undefined) that j will compute as zero inside the function,
: leading the function to conclude that the pointer is valid.
: The conclusion is utterly wrong, of course: the pointer aims
: not at the start of a T object, but one byte past the start
: of the first T object in the array.

: --
: (e-mail address removed)
 
E

Eric Sosman

Ike said:
Hi Eric,

: Ike Naar wrote:
:> int ptrInArrUnsafe(T *p,T *a,int max)
:> /* check whether p points to an element of a[max] */
:> {
:> int j=p-a; /* possibly undefined */
:> return 0<=j && j<max && a+j==p;
:> }
:>
: - ... and if this (or something like it) happens, the
: return expression will evaluate true, not false.

If 0<=j<max, the last conjuct (a+j==p) has to be false, due to the
initial assumption that p was not pointing to an element of a .

Ah, yes. Sorry about that; my reading comprehension
diminishes rapidly once the U.B. alarm bells start ringing.
Conversely, if the return expression evaluates true there would
have been no undefined behaviour, since in that case there exists
an index j such that 0<=j<max and &a[j]==p (that's what the return
expression implies), i.e. p points to an element of a, and
the pointer subtraction (p-a) would have been OK.

:> [...]
: But one need not invoke exotic architectures to get weird behavior
: out of violating the rules of pointer subtraction. For example,
: consider a "plain vanilla" system with nice linear addressing,
: where pointers are just unadorned numeric addresses. Now try
: this on for size:

: typedef char[8] T;

<nitpicking -- this is C.L.C. after all, isn't it?>
typedef char T[8];
</nitpicking>

Right again, and I've clearly become Java-polluted.
: T array[5];
: printf ("%d\n", ptrInArrUnsafe(&array[0][1], array, 5));

This is an extra complication that does not apply to the original problem
where p is supposed to have type T* . &array[0][1] is not a T* .

Right again, but this time it was just an editing error.
I'd started with

(T*)((char*)array + 1)

.... and lost the cast when simplifying. The first argument
ought to have been

(T*)&array[0][1]

Now, there are lots of opportunities for things to go wrong
with this. The conversion to T* might garble the address --
but in the example I was assuming a "plain vanilla" machine
on which that wouldn't happen. The pointer subtraction in
the function is still likely to yield zero by (more or less)
subtracting the two addresses to get 1 and then right-shifting
by three bits. It is, I guess, unlikely that a "plain vanilla"
machine would decide that (T*)&array[0][1] and array[0]+0 are
equal -- no guarantees, of course, but unlikely.

All in all, I'd say my attempt to express objections has
turned into an awful hash. Nonetheless ("Don't confuse me
with the facts; my mind is made up!") I'll still second CBF's
recommendation that shenanigans of this sort should be avoided,
or at the very least isolated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,362
Latest member
ChandaWagn

Latest Threads

Top