473,246 Members | 1,495 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

UB? Avoiding ``object'' before array's start

It's been a long time since I've posed a query here on c.l.c. My work
environment evolved to primarily C++ and Perl with very little C, so I've
forgotten quite a lot over time.

This revisits the much-discussed topic of decrementing a pointer to the
non-existent location before the start of an array. I've been re-reading
K.N. King's ``C Programming: A Modern Approach'' and came across
``reverse2.c'' on page 228, which raised a red flag. I presume most of the
regulars have access to the book or to the code (it's on the web).

Is the following, alternate approach (yes, I know there are other ways)
correct to interate backwards through the array without sniffing at the
non-existent element before the start of ``a''?

#include <stdio.h>

int main(void)
{
int *p, a[] = { 1, 2, 3 };
size_t n = sizeof a / sizeof *a;

for (p = a + n - 1; p + 1 >= a + 1; --p)
printf ("%i\n", *p);

return 0;
}


Jul 25 '06 #1
11 1415
Bob Nelson said:

<snip>
>
Is the following, alternate approach (yes, I know there are other ways)
correct to interate backwards through the array without sniffing at the
non-existent element before the start of ``a''?

#include <stdio.h>

int main(void)
{
int *p, a[] = { 1, 2, 3 };
size_t n = sizeof a / sizeof *a;

for (p = a + n - 1; p + 1 >= a + 1; --p)
a + n gives an only-just-legal but nevertheless legal reference to the
non-existent element a[n]. a + n - 1 is therefore fine. p + 1, on the first
iteration, points to that same only-just-legal non-existent element. And p
is never decremented below a. So yes, it's fine.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 25 '06 #2
Richard Heathfield wrote:
Bob Nelson said:

<snip>

Is the following, alternate approach (yes, I know there are other ways)
correct to interate backwards through the array without sniffing at the
non-existent element before the start of ``a''?

#include <stdio.h>

int main(void)
{
int *p, a[] = { 1, 2, 3 };
size_t n = sizeof a / sizeof *a;

for (p = a + n - 1; p + 1 >= a + 1; --p)

a + n gives an only-just-legal but nevertheless legal reference to the
non-existent element a[n]. a + n - 1 is therefore fine. p + 1, on the first
iteration, points to that same only-just-legal non-existent element. And p
is never decremented below a. So yes, it's fine.
p is never decremented below a? How can p + 1 >= a + 1 (p >= a) ever be
false, then?

Jul 25 '06 #3


Richard Heathfield wrote On 07/25/06 15:19,:
Bob Nelson said:

<snip>
>>Is the following, alternate approach (yes, I know there are other ways)
correct to interate backwards through the array without sniffing at the
non-existent element before the start of ``a''?

#include <stdio.h>

int main(void)
{
int *p, a[] = { 1, 2, 3 };
size_t n = sizeof a / sizeof *a;

for (p = a + n - 1; p + 1 >= a + 1; --p)


a + n gives an only-just-legal but nevertheless legal reference to the
non-existent element a[n]. a + n - 1 is therefore fine. p + 1, on the first
iteration, points to that same only-just-legal non-existent element. And p
is never decremented below a. So yes, it's fine.
"Let's play computer!"

Init: p = a+3-1 == p = a+2 (*p == 3)
Test: p+1 >= a+1 == a+3 >= a+1 == true
Body executes
Step: p = (a+2)-1 == p = a+1 (*p == 2)
Test: p+1 >= a+1 == a+2 >= a+1 == true
Body executes
Step: p = (a+1)-1 == p = a+0 (*p == 1)
Test: p+1 >= a+1 == a+1 >= a+1 == true
Body executes
Step: p = (a+0)-1 == UNDEFINED BEHAVIOR
Test: p+1 >= a+1 == UNDEFINED BEHAVIOR

The pair of "plus ones" in the test don't seem to have
any useful effect. Whenever they are valid (that is, whenever
p points to an actual element of a) they can be subtracted
from both sides, so the test is the same as `p >= a' in the
sense that both produce the same result or both are invalid.
The decorations do not expand the valid range.

To run a pointer backwards through an array, I suggest
writing the loop this way:

for (p = a + n; p a; ) {
--p;
/* loop body */
}

A slightly riskier form is

for (p = a + n; p-- a; ) {
/* loop body */
}

.... which sins by trying to compute the invalid pointer
value a-1, but avoids compounding the sin by doing further
arithmetic with that invalid value.

(I don't know what formulation King's book recommends.)

--
Er*********@sun.com

Jul 25 '06 #4
Eric Sosman said:
Richard Heathfield wrote On 07/25/06 15:19,:
>Bob Nelson said:
<snip>
>> for (p = a + n - 1; p + 1 >= a + 1; --p)

a + n gives an only-just-legal but nevertheless legal reference to the
non-existent element a[n]. a + n - 1 is therefore fine. p + 1, on the
first iteration, points to that same only-just-legal non-existent
element. And p is never decremented below a. So yes, it's fine.

"Let's play computer!"
Ouch. I lose. My apologies to the OP. I wasn't reading closely enough.

<snip>

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 25 '06 #5


Richard Heathfield wrote On 07/25/06 16:16,:
Eric Sosman said:
>>Richard Heathfield wrote On 07/25/06 15:19,:
>>>Bob Nelson said:

<snip>
>>> for (p = a + n - 1; p + 1 >= a + 1; --p)

a + n gives an only-just-legal but nevertheless legal reference to the
non-existent element a[n]. a + n - 1 is therefore fine. p + 1, on the
first iteration, points to that same only-just-legal non-existent
element. And p is never decremented below a. So yes, it's fine.

"Let's play computer!"


Ouch. I lose. My apologies to the OP. I wasn't reading closely enough.
Let him who has never committed an off-by-one error
cast the -1th stone.

--
Er*********@sun.com

Jul 25 '06 #6
Eric Sosman wrote:
Let him who has never committed an off-by-one error
cast the -1th stone.
Should that be the -1st ?

Jul 26 '06 #7
Old Wolf wrote:
Eric Sosman wrote:
> Let him who has never committed an off-by-one error
cast the -1th stone.


Should that be the -1st ?
See Figure abs(-1).

--
Eric Sosman
es*****@acm-dot-org.invalid
Jul 26 '06 #8
Bob Nelson wrote:
It's been a long time since I've posed a query here on c.l.c. My work
environment evolved to primarily C++ and Perl with very little C, so I've
forgotten quite a lot over time.

This revisits the much-discussed topic of decrementing a pointer to the
non-existent location before the start of an array. I've been re-reading
K.N. King's ``C Programming: A Modern Approach'' and came across
``reverse2.c'' on page 228, which raised a red flag. I presume most of the
regulars have access to the book or to the code (it's on the web).

Is the following, alternate approach (yes, I know there are other ways)
correct to interate backwards through the array without sniffing at the
non-existent element before the start of ``a''?

#include <stdio.h>

int main(void)
{
int *p, a[] = { 1, 2, 3 };
size_t n = sizeof a / sizeof *a;

for (p = a + n - 1; p + 1 >= a + 1; --p)
printf ("%i\n", *p);

return 0;
}

#include <stdio.h>

int main(void)
{
int a[] = { 1, 2, 3 };
size_t i, n = sizeof a / sizeof *a;

for (i = n - 1; i < n; --i)
printf ("%i\n", a[i]);

return 0;
}
--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jul 26 '06 #9
On Wed, 26 Jul 2006, Joe Wright wrote:
Bob Nelson wrote:
>It's been a long time since I've posed a query here on c.l.c. My work
environment evolved to primarily C++ and Perl with very little C, so I've
forgotten quite a lot over time.

This revisits the much-discussed topic of decrementing a pointer to the
non-existent location before the start of an array. I've been re-reading
K.N. King's ``C Programming: A Modern Approach'' and came across
``reverse2.c'' on page 228, which raised a red flag. I presume most of the
regulars have access to the book or to the code (it's on the web).

Is the following, alternate approach (yes, I know there are other ways)
correct to interate backwards through the array without sniffing at the
non-existent element before the start of ``a''?

#include <stdio.h>

int main(void)
{
int *p, a[] = { 1, 2, 3 };
size_t n = sizeof a / sizeof *a;

for (p = a + n - 1; p + 1 >= a + 1; --p)
printf ("%i\n", *p);

return 0;
}

#include <stdio.h>

int main(void)
{
int a[] = { 1, 2, 3 };
size_t i, n = sizeof a / sizeof *a;

for (i = n - 1; i < n; --i)
printf ("%i\n", a[i]);

return 0;
}
Are you taking the subject line literally? Your program
does in fact invoke UB, but I suspect that the OP wants
something /other/ than UB. For the subtitle was: `Avoiding
``object'' before array's start'.

Tak-Shing
Jul 26 '06 #10
On Thu, 27 Jul 2006, Tak-Shing Chan wrote:
On Wed, 26 Jul 2006, Joe Wright wrote:
>Bob Nelson wrote:
>>It's been a long time since I've posed a query here on c.l.c. My work
environment evolved to primarily C++ and Perl with very little C, so I've
forgotten quite a lot over time.

This revisits the much-discussed topic of decrementing a pointer to the
non-existent location before the start of an array. I've been re-reading
K.N. King's ``C Programming: A Modern Approach'' and came across
``reverse2.c'' on page 228, which raised a red flag. I presume most of the
regulars have access to the book or to the code (it's on the web).

Is the following, alternate approach (yes, I know there are other ways)
correct to interate backwards through the array without sniffing at the
non-existent element before the start of ``a''?

#include <stdio.h>

int main(void)
{
int *p, a[] = { 1, 2, 3 };
size_t n = sizeof a / sizeof *a;

for (p = a + n - 1; p + 1 >= a + 1; --p)
printf ("%i\n", *p);

return 0;
}

#include <stdio.h>

int main(void)
{
int a[] = { 1, 2, 3 };
size_t i, n = sizeof a / sizeof *a;

for (i = n - 1; i < n; --i)
printf ("%i\n", a[i]);

return 0;
}

Are you taking the subject line literally? Your program
does in fact invoke UB, but I suspect that the OP wants
something /other/ than UB. For the subtitle was: `Avoiding
``object'' before array's start'.
Sorry---I have overlooked the fact that you are using
size_t's. I retract my previous statement.

Your use of size_t in this context is quite clever (but the
loop condition of i < n is a bit misleading).

Tak-Shing
Jul 26 '06 #11
Tak-Shing Chan wrote:
On Thu, 27 Jul 2006, Tak-Shing Chan wrote:
>On Wed, 26 Jul 2006, Joe Wright wrote:
>>Bob Nelson wrote:
It's been a long time since I've posed a query here on c.l.c. My work
environment evolved to primarily C++ and Perl with very little C, so
I've
forgotten quite a lot over time.

This revisits the much-discussed topic of decrementing a pointer to the
non-existent location before the start of an array. I've been
re-reading
K.N. King's ``C Programming: A Modern Approach'' and came across
``reverse2.c'' on page 228, which raised a red flag. I presume most
of the
regulars have access to the book or to the code (it's on the web).

Is the following, alternate approach (yes, I know there are other ways)
correct to interate backwards through the array without sniffing at
the non-existent element before the start of ``a''?

#include <stdio.h>

int main(void)
{
int *p, a[] = { 1, 2, 3 };
size_t n = sizeof a / sizeof *a;

for (p = a + n - 1; p + 1 >= a + 1; --p)
printf ("%i\n", *p);

return 0;
}


#include <stdio.h>

int main(void)
{
int a[] = { 1, 2, 3 };
size_t i, n = sizeof a / sizeof *a;

for (i = n - 1; i < n; --i)
printf ("%i\n", a[i]);

return 0;
}

Are you taking the subject line literally? Your program
does in fact invoke UB, but I suspect that the OP wants
something /other/ than UB. For the subtitle was: `Avoiding
``object'' before array's start'.

Sorry---I have overlooked the fact that you are using
size_t's. I retract my previous statement.

Your use of size_t in this context is quite clever (but the
loop condition of i < n is a bit misleading).
Thank you.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jul 27 '06 #12

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

Similar topics

16
by: sneill | last post by:
How is it possible to take the value of a variable (in this case, MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name? In the following example I want 'oIcon' object to have...
6
by: Luke | last post by:
Here is my emails to Danny Goodman (but probably he is very busy so he didn't answered it). First email(simple): Subject: JavaScript Arrays " We all know the array can act like HashMap, but is...
6
by: Gary Frank | last post by:
What are the ramifications if I were to instantiate an object tens of thousands of times and add them to an array? Or hundreds of thousands of times? Do you know if the act of instantiating a...
2
by: gregory_may | last post by:
I am using a threadpool to process UDP broadcast messages. I cant figure out how to type the threadpool call back. Below is a snip of my code. The "process_UDP_Message" needs to pass a byte...
12
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. ...
4
by: rsa_net_newbie | last post by:
Hi there, I have a Managed C++ object (in a DLL) which has a method that is defined like ... Generic::List<String^>^ buildList(String^ inParm) Now, when I compile it, I get "warning C4172:...
14
by: mast2as | last post by:
Hi everyone, I am trying to implement some specs which specify that an array of parameter is passed to a function as a pointer to an array terminated by a NULL chatacter. That seemed fairly easy...
1
geo039
by: geo039 | last post by:
Okay I have an application, which is to demonstrate the use of a created class. I have a previous and next button which cycles through the array. However I need the user to be able to create a new...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, youll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.