This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: pointer math question



  In message <199803190613.WAA20961@cygint.cygnus.com>you write:
  > I have heard conflicting statements in the past about pointer math being
  > safe or unsafe.  Is pointer math safe or not?  Is malloc/realloc memory
  > always contiguous?  In the past I have always stayed away from pointer math
  > but I assume it may be faster than the alternative.
Pointer math is safe as long as you don't violate any ANSI C rules.

The key issue is that it is unsafe to ever perform arithmetic
on a pointer value which results in a pointer outside the range of
the original data item.    So assume I have a pointer to the 
start of an array of characters.  I can perform arithmetic on that
pointer so long as the result still points into that same array
of characters.

You can also subtract two pointers so long as they both point to the
same base object as well.  So given two pointers in an array of
characters, you can subtract them and that tells you exactly 
how many items exist between those two pointers.

As to your specific example, I believe it is safe.

The call to strchr will return a value in the array "out" (the address
of the first 'H' charcter).  Therefore cp-out has a well defined value
(the number of elements between "cp" and "out").


If the call to strchr failed to find the search character then the
program would have undefined results (strchr would return NULL,
which does not point into the same object as "out" and thus
cp-out has undefined results.


jeff


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]