473,756 Members | 3,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why pointer to "one past" is allowed but pointer to "one before" is not ?

Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ? Is there any reason why the
former is more useful than the later ?

Spiros Bousbouras

Jun 23 '06 #1
12 2047
sp****@gmail.co m wrote:
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ? Is there any reason why the
former is more useful than the later ?

Consider code such as

char *str = somestring;
while(*str++) {
...
}

str might end up one place past somestring - nice to allow that.
Jun 23 '06 #2

Nils O. Selåsdal wrote:
sp****@gmail.co m wrote:
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ? Is there any reason why the
former is more useful than the later ?

Consider code such as

char *str = somestring;
while(*str++) {
...
}

str might end up one place past somestring - nice to allow that.


Yes it is. My question was why the "opposite" is not allowed too.
One could have just as easily something like
while (source >= beg_of_string) *dest++ = *source-- ;
to copy a string in reverse for example.

Does my example evoke undefined behaviour by the way ?

Spiros Bousbouras

Jun 23 '06 #3
sp****@gmail.co m wrote:
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ?


Because a pointer one past any array need only take a single byte (since
only the address of the _first byte_ of the virtual member need be
valid, not any further ones), but a pointer one before the beginning
requires the assignment of memory space the size of an entire array
member. Given that the array member can be a humungous struct containing
arrays of structs of arrays of long doubles, this can cost a lot of
address space that could otherwise be gainfully employed.

Richard
Jun 23 '06 #4
Le 23-06-2006, sp****@gmail.co m <sp****@gmail.c om> a écrit*:
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ? Is there any reason why the
former is more useful than the later ?


More useful, yes if you agree than there are more
increasing loop than decreasing ones.

But I believe the real reason is that it is easier to
implement on hardware: you just have to waste 1
memory adress, that is to say, your processor
can adress from 0 up to 2^N-1, then, if all
data are stored bewteen 0 and 2^N-2, then,
'one position past' is at worst 2^N-1, which is
a valid adress for your processor, and pointer
arithmetic still apply.

But, 'one position before' is harder. You can not
have any bound on the size of the reserved memory
at the beginning. Because if an object of size S
is stored at adress N, then, &S+1 is just one char
after the space used to store S, but &S-1 is
'sizeof(S)' char before...

It's a bit hard to explain without any blackboard,
and I am not very good at ASCII art.

Marc Boyer
Jun 23 '06 #5
In article <44************ **@news.xs4all. nl>,
Richard Bos <rl*@hoekstra-uitgeverij.nl> wrote:
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ?
Because a pointer one past any array need only take a single byte (since
only the address of the _first byte_ of the virtual member need be
valid, not any further ones), but a pointer one before the beginning
requires the assignment of memory space the size of an entire array
member.


That's one reason, but I think a much more compelling one was that
there was lots of existing code that did things like

for(p=proc; p<procNPROC; p++)

and very little that did the reverse.

-- Richard
Jun 23 '06 #6
sp****@gmail.co m wrote:
Nils O. Selåsdal wrote:
sp****@gmail.co m wrote:
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ? Is there any reason why the
former is more useful than the later ?

Consider code such as

char *str = somestring;
while(*str++) {
...
}

str might end up one place past somestring - nice to allow that.


Yes it is. My question was why the "opposite" is not allowed too.


It's much,*much* more common to iterate this way, over the other way,
and probably was when the spec made :)
Jun 23 '06 #7
sp****@gmail.co m wrote:
...
Why is a pointer allowed to point to one position past
the end of an array but not to one position before the
beginning of an array ? Is there any reason why the
former is more useful than the later ?
...


There are several different reasons for that. One of them is described
below.

The storage is normally filled with the objects from smaller addresses
to larger addresses (i.e. in the same direction in which array indices
grow). For this reason, it is not unusual to have an object that resides
close to the beginning of the storage. To create a "before" pointer (and
properly support all pointer operations) for such an object might be
either impossible or unjustifiably difficult (since such a pointer would
have to point somewhere before the beginning of the storage). "Beginning
of the storage" in this case does not necessarily stand for the
beginning of physical memory. On a hardware platform with
segmented-memory the beginning of a segment has similar properties.

--
Best regards,
Andrey Tarasevich
Jun 23 '06 #8
sp****@gmail.co m wrote:
...
Yes it is. My question was why the "opposite" is not allowed too.
One could have just as easily something like
while (source >= beg_of_string) *dest++ = *source-- ;
to copy a string in reverse for example.

Does my example evoke undefined behaviour by the way ?
...


Formally, it does lead to UB, since it attempts to create a "one before"
pointer.

The problem with your code in its nature is similar to the problem with
the following code

unsigned i;
...
while (i >= 0) dest[i] = source[i--];

Note that an unsigned value will never be negative and the loop will
never end.

Essentially the same thing can happen in case of a pointer. If we think
consider pointers (addresses) as arithmetic values, they are unsigned.
Imagine that your 'beg_of_string' pointer points to address 0. How do
you expect you loop to end in this case? How do you expect to represent
a pointer that is less than '0'?

--
Best regards,
Andrey Tarasevich
Jun 23 '06 #9
On Fri, 23 Jun 2006 05:40:43 -0700, spibou wrote:

Nils O. Selåsdal wrote:
sp****@gmail.co m wrote:
> Why is a pointer allowed to point to one position past the end of an
> array but not to one position before the beginning of an array ? Is
> there any reason why the former is more useful than the later ?

Consider code such as

char *str = somestring;
while(*str++) {
...
}
}
str might end up one place past somestring - nice to allow that.


Yes it is. My question was why the "opposite" is not allowed too. One
could have just as easily something like while (source >= beg_of_string)
*dest++ = *source-- ; to copy a string in reverse for example.

Does my example evoke undefined behaviour by the way ?


Yes. And to see a real world example of such a program failing because of
this (not that undefined means it must fail), try this compiler

http://fabrice.bellard.free.fr/tcc/

w/ your code, using the -b switch (bounds checker). I never heeded the
standard on this point until I started using TCC to improve my code
portability.

I must say there are some circumstances where it is indeed desirable to
iterate backwards. For example, I had to tweak many places in a memory
pool library because I would iterate backwards from a given pointer
reading bookkeeping information until I hit a terminator bit. Took me hours to
figure out why my program would crash using TCC:

/*
* Beginning from *p, work backwards reconstructing the value of an
* rbitsint_t integer. Stop when the highest order bit of *p is set, which
* should have been previously preserved as a marker. Return the
* reconstructed value, setting *end to the last position used of p.
*/
static inline rbitsint_t rbits_get(unsig ned char *p, unsigned char **end) {
rbitsint_t i = 0; /* currently typedef to size_t */
int n = 0;

do {
i |= (*p & ~(1 << (CHAR_BIT - 1))) << (n++ * (CHAR_BIT - 1));
} while (!(*(p--) & (1 << (CHAR_BIT - 1))));

*end = p + 1;

return i;
} /* rbits_get() */
Jun 23 '06 #10

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

Similar topics

1
2734
by: Christian Seberino | last post by:
I specify packages in my setup.py but what if I want all py files in a directory but one??? How remove just that one?? (Without listing all files I want explicitly??) I need header files to build a C extension but I DON't want headers installed. *How do I include header files in the tar.gz (tarball) file but NOT have them be installed when "python setup.py install" done??
8
1416
by: Allen | last post by:
Hi all, I have a tree object I'm writing that searches itself using a recursive search. Thing is, I'm wanting to also include the ability to simply transfer execution if I want ("one-way recursion"). _One problem_ with doing it this way is stack overflow. What I'm thinking of doing is using "naked" function calls for the recursive search so that if I want to simply transfer execution, I could clean up the stack myself. This seems an...
26
2995
by: Michel Rouzic | last post by:
I have a binary file used to store the values of variables in order to use them again. I easily know whether the file exists or not, but the problem is, in case the program has been earlier interupted before it could write the variables to the file, the file is gonna be empty, and then it's gonna load a load of crap into variables, which i want to avoid. That file is always 36 bytes big (it contains 4 double-precision floats and one...
8
21912
by: Grant Richard | last post by:
Using the TcpListener and TcpClient I created a program that just sends and receives a short string - over and over again. The program is fine until it gets to around 1500 to 1800 messages. At that time, I get a SocketException with the message "Only one usage of each socket address (protocol/network address/port) is normally permitted". This happen if you use localhost or between two distinct computers. And, for a period of time after the...
1
1942
by: wxqun | last post by:
Our company is now trying to make a "standard" of creating a base view for each user table. This initiative is suggested as a good practice by a data modeling consultant who is helping us to build DW logical/physical model. He pointed out that the work and risk of making a database change will be reduced by using the "base view". Since this base view is just a selection of all user table's columns, as DBA, I don't see any reasons for...
0
1513
by: 2Barter.net | last post by:
" Given BACK what was freely GIVEN " More options 2 messages - Expand all 2Barter.net View profile More options Dec 12, 9:48 pm Blessing Are Country
4
1372
by: rempit | last post by:
In 1 form..have 2 "DIV".. "DIV" one is for SEARCH.. "DIV" two is for showing the RESULT from Database of "DIV" one Button.. Everything in one page.. Anyone can help me please..
0
9456
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9275
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
10034
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9872
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9843
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8713
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 project—planning, coding, testing, and deployment—without 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...
0
5142
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2666
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.