473,732 Members | 2,205 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1442
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

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

Similar topics

16
25418
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 the properties: mode1, mode2, and mode3. This seems simple but I can't quite figure it out... Any ideas anyone?
6
2342
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 there a shortcut for creating such array ? eg //simple array indexed via numbers var a = new Array("a", "fdsf", "sada"); or,
6
1626
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 class takes a lot of storage or other resources? Would it be a severe performance penalty? From the .Net help doc:
2
1094
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 array .... but the Call Back only passes back a generic object. Anyone know how I can force the type of "receiveBuffer" when I make the call to process_UDP_Message? 'Main processing loop: If Not ThreadPool.QueueUserWorkItem _ (New...
12
5555
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. Foo = function(type) { this.num = 0; this.type = type this.trigger(); } Foo.prototype.trigger = function() {
4
2954
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: returning address of local variable or temporary". In good old 'C', that would indicate that a 'static' was missing from the declaration of the returned value.
14
3020
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 to implement. I had a special Malloc function that would allocated the number of needed bytes for the objects i needed to store + 1 additional byte to save the NULL character /*!
1
1342
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 instance of the object then as they cycle through they see their new object. I am stuck on this part. I've tried a few things for my button create event but I have been getting an unhandled can't convert to 1 dimensional array among other things. Any...
0
8774
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
9447
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
9307
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
9235
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
9181
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...
1
6735
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
6031
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();...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.