473,508 Members | 2,382 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Contiguous storage of ints?

Saw this used as an example. Compiles without warnings. "Works."
Kosher or not?
Why or why not?

#include <stdio.h>
int main(int argc, char **argv){
int i,j,k,l,m;
int *p;
i=2; j=4; k=8; l=32; m=64; /*any values*/
p = &i;
*p = *p+1;
*(p+1) = *(p+1) +1;
*(p+2) = *(p+2) -1;
printf("{i,j,k,l,m}={%d,%d,%d,%d,%d}\n", i,j,k,l,m);
return 0;
}
Oct 5 '06 #1
9 2042
In article <2xgVg.787$rS.221@fed1read05>,
jmcgill <jm*****@email.arizona.eduwrote:
>Kosher or not?
Why or why not?

int i,j,k,l,m;
int *p;
i=2; j=4; k=8; l=32; m=64; /*any values*/
p = &i;
*p = *p+1;
*(p+1) = *(p+1) +1;
*(p+2) = *(p+2) -1;
No, of course not.

It's not even a "works on all common platforms" case - I get
this when I run it on the machine I'm using:

-bash-2.05b$ ./foo
{i,j,k,l,m}={3,4,8,32,64}
Segmentation fault: 11 (core dumped)

-- Richard
Oct 5 '06 #2
jmcgill <jm*****@email.arizona.eduwrites:
Saw this used as an example. Compiles without warnings. "Works."
Kosher or not?
Why or why not?

#include <stdio.h>
int main(int argc, char **argv){
int i,j,k,l,m;
int *p;
i=2; j=4; k=8; l=32; m=64; /*any values*/
p = &i;
*p = *p+1;
*(p+1) = *(p+1) +1;
*(p+2) = *(p+2) -1;
printf("{i,j,k,l,m}={%d,%d,%d,%d,%d}\n", i,j,k,l,m);
return 0;
}
This invokes undefined behavior. If it happens to work, it's only by
accident.

p points to an int object, i. p+1 points just past that object, which
is ok (a single object is treated in this context as an array of one
element, and you can legally point just past the last element of an
array). Dereferencing p+1 invokes undefined behavior, since it
doesn't point to any object. Likewise for p+2.

Note that two pointers are *allowed* to compare equal if one points
just past the end of an object, another points to an object, and the
two objects happen to be allocated adjacently in memory. This is not
a license to *assume* that objects declared next to each other in
source will be allocated adjacently in memory.

You ask why it's not "kosher". A better question is, why do you
assume that it is? An implementation could allocate i, j, k, l, and m
with gaps between them, and fill each gap with a moat full of angry
crocodiles. Or, more realistically, it might allocate them in reverse
or arbitrary order. Or a debugging implementation might create gaps
that you can't access without causing a trap, to catch just the kind
of error you're making here. If you can find a clause in the standard
that forbids any of these, you might have an argument that the
behavior of your program is defined.

If you adjacent objects of the same type, declare an array. (I'm
guessing, though, that your goal was to learn about the code you
posted, not to achieve some particular programming goal.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 5 '06 #3


On Oct 5, 4:29 pm, jmcgill <jmcg...@email.arizona.eduwrote:
Saw this used as an example. Compiles without warnings. "Works."
The program segfaults when I compiled and ran it.
Kosher or not?
Why or why not?
It's not "kosher" because the C standard
does not guarantee that successively
declared variables occupy a contiguous
region of addressable memory.
#include <stdio.h>
int main(int argc, char **argv){
int i,j,k,l,m;
int *p;
i=2; j=4; k=8; l=32; m=64; /*any values*/
p = &i;
*p = *p+1;
Okay so far.
*(p+1) = *(p+1) +1;
p+1 is not guaranteed to be the address of j.
*(p+2) = *(p+2) -1;
and so on...
printf("{i,j,k,l,m}={%d,%d,%d,%d,%d}\n", i,j,k,l,m);
return 0;

}

This can work if you use an array of int:

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
int contiguous[] = { 2, 4, 8, 32, 64 };
int *p;
p = contiguous;
*p = *p+1;
*(p+1) = *(p+1) + 1;
*(p+2) = *(p+2) - 1;
printf("{i,j,k,l,m}={%d,%d,%d,%d,%d}\n",
contiguous[0],
contiguous[1],
contiguous[2],
contiguous[3],
contiguous[4]
);
return EXIT_SUCCESS;
}

--
Hope this helps,
Steven

Oct 5 '06 #4
Keith Thompson wrote:
You ask why it's not "kosher". A better question is, why do you
assume that it is?
CS professor with a zillion years of experience presented it with a
straight face as an example.

I *know* it's undefined behavior, I pointed this out, and I found myself
on the right side in an uncomfortable argument.
Oct 5 '06 #5
at*************@gmail.com wrote:
>
On Oct 5, 4:29 pm, jmcgill <jmcg...@email.arizona.eduwrote:
>Saw this used as an example. Compiles without warnings. "Works."

The program segfaults when I compiled and ran it.
>Kosher or not?
Why or why not?

It's not "kosher" because the C standard
does not guarantee that successively
declared variables occupy a contiguous
region of addressable memory.
I didn't think so either, but I made the mistake of not keeping my mouth
shut when it was presented as an example to an intro course, where the
example is abusing the ints as if they were an array, because the people
in this course have not yet been exposed to arrays.

I personally know C in far more depth than this intro course, but I was
concerned that people might learn a bad habit from this example. It
happens to work on certain platforms, and in the absence of a concrete
counterexample (like a line in K&R that says "if you do this you should
be shot"), I don't really want to argue against the idea.

I wish I had a machine that would make this segfault. I *know* it can't
be right in the general case. The compiler is free to use registers for
the vars that have not explicitly had their addresses assigned by an
address-of operator, at the very least, correct?

Oct 5 '06 #6
jmcgill wrote:
>
I wish I had a machine that would make this segfault. I *know* it can't
be right in the general case. The compiler is free to use registers for
the vars that have not explicitly had their addresses assigned by an
address-of operator, at the very least, correct?
As it happens on my Solaris X86 box:
gcc -Wall -pedantic -ansi /tmp/x.c
a.out
{i,j,k,l,m}={3,4,8,32,64}
Segmentation Fault (core dumped)

Sun's cc optimises the code thus:

main:
subl $4,%esp ;/ line : 10
push $64 ;/ line : 10
push $32 ;/ line : 10
push $8 ;/ line : 10
push $4 ;/ line : 10
push $3 ;/ line : 10
push $.L97 ;/ line : 10
call printf ;/ line : 10
addl $28,%esp ;/ line : 10
xorl %eax,%eax ;/ line : 11
ret ;/ line : 11

Which I'd expect most compilers to do. So the perverse use of pointers
is disguised by optimisation.

--
Ian Collins.
Oct 6 '06 #7

jmcgill wrote:
at*************@gmail.com wrote:

On Oct 5, 4:29 pm, jmcgill <jmcg...@email.arizona.eduwrote:
Saw this used as an example. Compiles without warnings. "Works."
The program segfaults when I compiled and ran it.
Kosher or not?
Why or why not?
It's not "kosher" because the C standard
does not guarantee that successively
declared variables occupy a contiguous
region of addressable memory.

I didn't think so either, but I made the mistake of not keeping my mouth
shut when it was presented as an example to an intro course, where the
example is abusing the ints as if they were an array, because the people
in this course have not yet been exposed to arrays.
Yes, your teacher is wrong.
I personally know C in far more depth than this intro course, but I was
concerned that people might learn a bad habit from this example. It
happens to work on certain platforms, and in the absence of a concrete
counterexample (like a line in K&R that says "if you do this you should
be shot"), I don't really want to argue against the idea.

I wish I had a machine that would make this segfault. I *know* it can't
be right in the general case. The compiler is free to use registers for
the vars that have not explicitly had their addresses assigned by an
address-of operator, at the very least, correct?
Not so free. In fact, the clever compilers will arrange the most
frequently used vars in registers and make other in the memory, if they
desire speed.

Oct 6 '06 #8
jmcgill said:
Saw this used as an example. Compiles without warnings. "Works."
Kosher or not?
Why or why not?

#include <stdio.h>
int main(int argc, char **argv){
int i,j,k,l,m;
int *p;
i=2; j=4; k=8; l=32; m=64; /*any values*/
p = &i;
*p = *p+1;
*(p+1) = *(p+1) +1;
*(p+2) = *(p+2) -1;
printf("{i,j,k,l,m}={%d,%d,%d,%d,%d}\n", i,j,k,l,m);
return 0;
}
I sympathise with your motivation for asking, and of course it's obvious
that it isn't kosher. It isn't even halal. Here's the output on my system:

{i,j,k,l,m}={3,4,8,32,64}
Segmentation fault (core dumped)

Let's now investigate why the program is incorrect.

#include <stdio.h>
int main(int argc, char **argv){

argc and argv are not used, but apart from that we're looking good so far.

int i,j,k,l,m;
int *p;

Well, okay.

i=2; j=4; k=8; l=32; m=64; /*any values*/

Still legal.

p = &i;

p points to i. So *p has the value 2.

*p = *p+1;

*p (i.e. i) now has the value 3.

*(p+1) = *(p+1) +1;

It is legal to form the pointer p + 1, since i can be considered "as if" it
were an array of one int, and it is legal to point one past the end of an
array. It is not, however, legal to dereference that pointer, which this
code does. Chapter and verse is in:

3.3.6 Additive operators:

[...] When an expression that has integral type is added to or subtracted
from a pointer, the integral value is first multiplied by the size of the
object pointed to. The result has the type of the pointer operand. If the
pointer operand points to a member of an array object, and the array object
is large enough, the result points to a member of the same array object,
appropriately offset from the original member. Thus if P points to a
member of an array object, the expression P+1 points to the next member of
the array object. Unless both the pointer operand and the result point to
a member of the same array object, or one past the last member of the array
object, the behavior is undefined.

So whoever wrote the program needs to learn C before they try teaching it.

--
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)
Oct 6 '06 #9
jmcgill posted:
int i,j,k,l,m;

int arr[5];

#define i (arr[0])
#define j (arr[1])
#define k (arr[2])
#define l (arr[3])
#define m (arr[4])

/* Use them... */

#undef i
#undef j
#undef k
#undef l
#undef m

--

Frederick Gotham
Oct 6 '06 #10

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

Similar topics

0
1648
by: Newsgroup - Ann | last post by:
Hi: I saw the following codes from the FAQ about the contiguous storage of vector. I am just wondering how does the implementation of the <vector> guarantee the contiguous? What if a vector v...
2
1779
by: LeTubs | last post by:
Hi I have few questions in realtion to arrays, I assume that they are not available as a data type, is this correct ? The reason why is that I want to store a large amount of data for a...
8
2370
by: Ravi | last post by:
Is a std::vector *guaranteed* to be contiguous in memory? Bjarne Stroustrup says it takes constant time to access a vector element and that implies contiguous storage but I just wanted to...
3
1506
by: Dave Rahardja | last post by:
Where is it specified that data storage for <vector> must be contiguous? i.e., Assuming v is a vector of some size, &v == &v + 1; -dr
38
5081
by: Peteroid | last post by:
I looked at the addresses in an 'array<>' during debug and noticed that the addresses were contiguous. Is this guaranteed, or just something it does if it can? PS = VS C++.NET 2005 Express...
22
3072
by: divya_rathore_ | last post by:
No pun intended in the subject :) Is dynamically allocated memory contiguous in C++? In C? Deails would be appreciated. warm regards, Divya Rathore (remove underscores for email ID)
22
2596
by: Jack | last post by:
The following code can be compiled. But When I run it, it causes "Segmentation fault". int main(){ char **c1; *c1 = "HOW"; // LINE1 ++(*c1); *c1 = "ARE";
74
4493
by: aruna.mysore | last post by:
Hi all, I have a simple definitioin in a C file something like this. main() { char a; ....... int k; }
14
2105
by: Richard Harter | last post by:
Apologies for the length - this post is best viewed with fixed font and a line width >= 72. Below is the source code for a C header file that provides a suite of storage management macros. I am...
0
7223
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,...
0
7321
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,...
0
7377
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...
1
7036
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...
0
7489
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...
0
5624
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,...
1
5047
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...
0
3191
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...
0
3179
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.