473,883 Members | 1,809 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointer arithmetic questions

Is the following code ISO C++ standard compliant?
If yes, is it guaranteed that it will not crash on compliant platforms?
If yes, will it print "Pointers are equal" on any compliant platform?
Will answers be the same if p points to local memory or string literal?
char *p = new char[10];
char *p1 = p-1;
p1 = p1 + 1;

if(p1 == p)
{
cout << "Pointers are equal" << endl;
}

Thank you,

Michael

Jul 23 '05
21 2102
James Aguilar wrote:

It's not compliant, but I'd honestly be amazed if you could find me a
compiler/runtime environment combination that failed to run it and give you the
output you expect.


Win16 with a memory manager that returns blocks in distinct segments;
you can't address below 0 within a segment (it wraps around, and faults
because it's out of range).

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #11
"Pete Becker" wrote
BigBrian wrote:

Your comment seems to imply that there's something checking the end
points of the array.


Nope.
There is not. You *can* go in front. You can
even do pointer arithmetic on a pointer that's not even pointing to an
array. It compiles,


Not necessarily. The behavior is undefined, and that means you cannot
count on anything in particular. There is nothing in the language
definition that requires this code to compile. Don't use compilers to
test code conformance.

By the way, when most people say "you can't to that" there's an implied
"in conforming code."


Sorry, I don't get it. Why should it not compile? A ptr is just a ptr, it can
point anywhere.
Jul 23 '05 #12
Alvin wrote:
Pete Becker wrote:
Alvin wrote:

I would say this is standard compliant (without looking it up).


Then you'd better look it up. <g> The rule for pointer
arithmetic is that you can move around within an array
or to one position past the end. You can't go in front
of the beginning.


I guess I didn't make myself clear. By standard compliant I was
trying to say p1 = p-1 was compliant. I didn't intend on saying
the result was compliant.


The expression (p-1) causes undefined behaviour.

Jul 23 '05 #13
> By the way, when most people say "you can't to that" there's an
implied
"in conforming code."


I'll try to remember that your messages have an implied "in conforming
code", however, it may be easier if you just include it so there's no
confusion.

-Brian

Jul 23 '05 #14
I can't believe that
char *p1 = p-1; //(1)
p1 = p1 + 1; //(2)
causes undefined behavior as noted by Old Wolf.

I would really like to know why is it so, please someone explain why?

As far as I'm concerned the code is valid if there's substraction and
addition for pointers defined (which is defined). In short
line 1: p1 = address_of(p) - 1*sizeof(*p);
line 2 p1 = address_of(p1) + 1*sizeof(*p1);
how is that phisically may trigger any sort of problem unless generated
code tests result of every pointer operation? Basicly on the first line
p1 is assigned address of the char that precedes (*p) and even if it's
0 why then p1 = 0 should be any different from p1 = p-1???
Even if it wraps in win16 as noted by Pete Becker I still don't
understand what causes segfault?!? The behavior would be surely
undefined if the OP tried to access the char pointed by p1 before line2
was executed. Basicly from machine code it's absolutely valid, but
probably c++ forbids such arithmetics (why?!?)... please explaint
better someone who knows!

Thanks

Jul 23 '05 #15
bl******@mail.r u wrote:
I would really like to know why is it so, please someone explain why?
You've been told why. Please read the messages.
As far as I'm concerned the code is valid if there's substraction and
addition for pointers defined (which is defined).


No, it's only defined over the space of a single object. The issue is
machines where there are segments or banks mean a pointer isn't just a
byte offset from the beginning of address space. There's no
requirement that the thing graciously roll negative off the beginning
of a segment. Because of decades of bad programming assumptions, going
off by one the other way was deemed to be acceptible.

While C++ puts no bounds on the errors that might come from exploiting
undefined behavior, a very real one is that
(ptr - 1) + 1
doesn't put you back at the original ptr value.

Jul 23 '05 #16
Uenal Mutlu wrote:
"Pete Becker" wrote
BigBrian wrote:

Your comment seems to imply that there's something checking the
end points of the array.


Nope.
There is not. You *can* go in front. You can
even do pointer arithmetic on a pointer that's not even pointing
to an array. It compiles,


Not necessarily. The behavior is undefined, and that means you
cannot count on anything in particular. There is nothing in the
language definition that requires this code to compile. Don't
use compilers to test code conformance.


Sorry, I don't get it. Why should it not compile? A ptr is just
a ptr, it can point anywhere.


Wrong. A pointer must either be null, indeterminate, or
point to part of an object that exists (or point to a function).

You might be used to some systems (eg. Windows 95) where a pointer
can point anywhere, but that does not apply to all possible systems.

One such example: a CPU could generate a hardware exception
when one of its address registers is loaded with an invalid
address, or an address not owned by the current thread.
So when you go (p - 1) you are trying to point to a different
thread's memory, and the CPU immediately kills the thread for
an access violation.

Another good example was given by Pete Becker: why should a
system have to do anything sensible if you subtract 1 from
an address of 0 ? What is (1000:0) - 1? (ie. segment 1000 offset 0)

Jul 23 '05 #17
bl******@mail.r u wrote:
I can't believe that
char *p1 = p-1; //(1)
p1 = p1 + 1; //(2)
causes undefined behavior as noted by Old Wolf.

I would really like to know why is it so, please someone explain why?

As far as I'm concerned the code is valid if there's substraction and
addition for pointers defined (which is defined). In short
line 1: p1 = address_of(p) - 1*sizeof(*p);
line 2 p1 = address_of(p1) + 1*sizeof(*p1);
how is that phisically may trigger any sort of problem unless generated
code tests result of every pointer operation? Basicly on the first line
p1 is assigned address of the char that precedes (*p) and even if it's
0 why then p1 = 0 should be any different from p1 = p-1???
Even if it wraps in win16 as noted by Pete Becker I still don't
understand what causes segfault?!? The behavior would be surely
undefined if the OP tried to access the char pointed by p1 before line2
was executed. Basicly from machine code it's absolutely valid, but
probably c++ forbids such arithmetics (why?!?)... please explaint
better someone who knows!

Thanks


Read ISO9899:1999 section 6.5.6 paragraph 8:

<quote>
When an expression that has integer type is added to or subtracted from
a pointer, the
result has the type of the pointer operand. If the pointer operand
points to an element of
an array object, and the array is large enough, the result points to an
element offset from
the original element such that the difference of the subscripts of the
resulting and original
array elements equals the integer expression. In other words, if the
expression P points to
the i-th element of an array object, the expressions (P)+N
(equivalently, N+(P)) and
(P)-N (where N has the value n) point to, respectively, the i+n-th and
i−n-th elements of
the array object, provided they exist. Moreover, if the expression P
points to the last
element of an array object, the expression (P)+1 points one past the
last element of the
array object, and if the expression Q points one past the last element
of an array object,
the expression (Q)-1 points to the last element of the array object. If
both the pointer
operand and the result point to elements of the same array object, or
one past the last
element of the array object, the evaluation shall not produce an
overflow; otherwise, the
behavior is undefined. If the result points one past the last element of
the array object, it
shall not be used as the operand of a unary * operator that is evaluated.
</quote>

especially the last two sentences...

Tom
Jul 23 '05 #18
Thomas Maier-Komor wrote:
bl******@mail.r u wrote:
I can't believe that
char *p1 = p-1; //(1)
p1 = p1 + 1; //(2)
causes undefined behavior as noted by Old Wolf.

I would really like to know why is it so, please someone explain why?

As far as I'm concerned the code is valid if there's substraction and
addition for pointers defined (which is defined). In short
line 1: p1 = address_of(p) - 1*sizeof(*p);
line 2 p1 = address_of(p1) + 1*sizeof(*p1);
how is that phisically may trigger any sort of problem unless generated
code tests result of every pointer operation? Basicly on the first line
p1 is assigned address of the char that precedes (*p) and even if it's
0 why then p1 = 0 should be any different from p1 = p-1???
Even if it wraps in win16 as noted by Pete Becker I still don't
understand what causes segfault?!? The behavior would be surely
undefined if the OP tried to access the char pointed by p1 before line2
was executed. Basicly from machine code it's absolutely valid, but
probably c++ forbids such arithmetics (why?!?)... please explaint
better someone who knows!

Thanks


Read ISO9899:1999 section 6.5.6 paragraph 8:

<quote>
When an expression that has integer type is added to or subtracted from
a pointer, the
result has the type of the pointer operand. If the pointer operand
points to an element of
an array object, and the array is large enough, the result points to an
element offset from
the original element such that the difference of the subscripts of the
resulting and original
array elements equals the integer expression. In other words, if the
expression P points to
the i-th element of an array object, the expressions (P)+N
(equivalently, N+(P)) and
(P)-N (where N has the value n) point to, respectively, the i+n-th and
i−n-th elements of
the array object, provided they exist. Moreover, if the expression P
points to the last
element of an array object, the expression (P)+1 points one past the
last element of the
array object, and if the expression Q points one past the last element
of an array object,
the expression (Q)-1 points to the last element of the array object. If
both the pointer
operand and the result point to elements of the same array object, or
one past the last
element of the array object, the evaluation shall not produce an
overflow; otherwise, the
behavior is undefined. If the result points one past the last element of
the array object, it
shall not be used as the operand of a unary * operator that is evaluated.
</quote>

especially the last two sentences...

Tom


sorry that was the wrong standard...
but in ISO14882 section 5.7 paragraph 5 the text is almost the same:

<quote>
When an expression that has integral type is added to or subtracted from
a pointer, the result has the type of
the pointer operand. If the pointer operand points to an element of an
array object, and the array is large
enough, the result points to an element offset from the original element
such that the difference of the subscripts
of the resulting and original array elements equals the integral
expression. In other words, if the
expression P points to the i-th element of an array object, the
expressions (P)+N (equivalently, N+(P))
and (P)-N (where N has the value n) point to, respectively, the i+n-th
and i–n-th elements of the array
object, provided they exist. Moreover, if the expression P points to the
last element of an array object, the
expression (P)+1 points one past the last element of the array object,
and if the expression Q points one
past the last element of an array object, the expression (Q)-1 points to
the last element of the array object.
If both the pointer operand and the result point to elements of the same
array object, or one past the last element
of the array object, the evaluation shall not produce an overflow;
otherwise, the behavior is undefined.
</quote>

Tom
Jul 23 '05 #19
in other words according to the standard
unsigned char* some_random_add ress = 0xabc12345;
has undefined behavior becase it doesn't point to an array element or
one past the array... It simply means that I cannot have a pointer to
an arbitrary element in memory (even if no such area addressable etc
etc, but I just cannot have an arbitraty address)?, it seems to be very
strange if not ridiculous. If programming in asembler there's no
difference wether a pointer points to first, last, arbitrary memory, 0,
0-1 ... all comes up when you access this regions by the pointer.
It's very surprising for me to know about that, thanks for the info
Tom.

ps. anyways, I can't believe that the code of original poster could
have any other behavior than printing that the pointers are equal. Even
it's win16 or whatever as long as the generated code doesn't checks the
result of every pointer operation not to point to arbitrary memory then
it should not have any problems. Maybe in C it's ok to do so? :)

Jul 23 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2196
by: ceo | last post by:
Hi, Following is a program that doesn't give the expected output, not sure what's wrong here. I'm adding the size of derived class to the base class pointer to access the next element in the array. Why does bp point to some address that is not &d? Please clarify. Thanks,
22
12764
by: Alex Fraser | last post by:
From searching Google Groups, I understand that void pointer arithmetic is a constraint violation, which is understandable. However, generic functions like qsort() and bsearch() must in essence do exactly this, and similarly generic functions seem to have useful applications. In a few posts I read, it was suggested to avoid void pointer arithmetic by casting to a char pointer, and performing arithmetic on that (in multiples of...
3
7668
by: sathyashrayan | last post by:
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var = {NULL};
6
2298
by: Francois Grieu | last post by:
Are these programs correct ? #include <stdio.h> unsigned char a = {1,2}; int main(void) { unsigned char j; for(j=1; j<=2; ++j) printf("%u\n", *( a+j-1 )); return 0; }
7
528
by: barikat | last post by:
int a; int *Ptr1, *Ptr2; Ptr1 = a; Ptr1++; Ptr2 = a; printf("Ptr1 : %p\n", Ptr1); printf("Ptr2 : %p\n\n", Ptr2);
26
3076
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I read some of the items from the bottom up of the buffer, and some from the top down, moving the bottom items back to the new re-allocated bottom on every file read. Then when I've read all four files, I sort the top and bottom items separately...
19
3916
by: =?iso-8859-1?b?VG9t4XMg0yBoyWlsaWRoZQ==?= | last post by:
Coming originally from C++, I used to do the likes of the following, using a pointer in a conditional: void Func(int *p) { if (p) { *p++ = 7; *p++ = 8;
25
2029
by: Ioannis Vranos | last post by:
Are the following codes guaranteed to work always? 1. #include <iostream> inline void some_func(int *p, const std::size_t SIZE) {
8
1869
by: tfelb | last post by:
Hey group! I have 2 questions. I saw functions with char *dst = (char *)src. In that case if I remember what I've learned I assign (an) (the) address of src to dst. Right? But I can assign an address with the address operator & too? char *dst = &src. What's the difference between *dst = (char *)src and *dst = &src and
0
9942
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9792
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10416
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9574
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7971
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7129
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4612
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4220
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3233
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.