Re: Neatest way to get the end pointer?



vipps...@xxxxxxxxx wrote:
Keith Thompson <ks...@xxxxxxx> wrote:
vipps...@xxxxxxxxx writes:
"Tomás Ó hÉilidhe" <t...@xxxxxxxxxxx> wrote:
I commonly use pointers to iterate thru an array.
For example:
    int my_array[X];
[snip]
1) my_array is an int[X]
2) &my_array is an int(*)[X]
3) &my_array+1 is the address of the non-existant
array located after the current one.

And you invoke undefined behavior.

No, he doesn't.  &my_array+1 is a valid address,

Though it requires a conversion back to int * if used
as a pointer 'index' compared against an int * iterator.

just past the end of my_array.  Computing this address
is ok; attempting to dereference it would invoke UB.

I think that when the result of an expression is a non-
valid pointer, the behavior is undefined.

True, but one byte past the end of an array _is_ a valid
pointer.

Correct me if I am wrong,

Keith already has.

but I have also seen comments in GNU code like this:
--
/* ANSI C violation */
char * s = p - 1;

One byte beyond is fine (though you can't dereference it),
but there are no special rights for one (or more) byte(s)
_before_.

--
Where p points to the start of a string passed. 's' is
never dereferenced, ...

Doesn't matter. Implementations do not have to cope with
'one byte before'. An allocation can be made at the start
of a memory page. Merely calculating an address prior to
such a page may trap. In contrast, implementations _must_
cope with one byte beyond, which simply means that at
least one byte (but typically _at most_ one byte) is
reserved at the end of the memory space.

--
Peter
.



Relevant Pages

  • Re: Pointer assigning.
    ... element) to the object pointed to by ptr2. ... int *ptr2 = NULL; ... want to - we were mistaken in adding a dereference operator). ... All we want is to assign a pointer value to ptr2. ...
    (comp.lang.c)
  • Re: link pointer access problem
    ... int b_value; ... be a null pointer ... dereference a pointer with an indeterminate value. ...
    (comp.lang.c)
  • Re: The difference between 0 and NULL?
    ... There's a real distinction here between assigning a null pointer ... and assigning all-bits-zero where a null pointer is NOT all-bits-zero. ... If you take *ANY* integer constant, assign it to an int variable, ... and then cast it to a pointer and dereference it, ...
    (comp.unix.programmer)
  • Re: "float* f" vs. "float *f"
    ... int i, *j; ... because `*j' is how I'd dereference `j' in an expression. ... which is not that different (function pointer syntax as well as arrays is a special case anyway). ... unsigned char *const *bibble; ...
    (comp.lang.c.moderated)
  • Re: Typecasting Pointers on a 64 bit System
    ... MacOS X 64 bit and probably on other 64 bit systems casting an int to ... and that therefore the result is always a null pointer. ...
    (comp.lang.c)