473,661 Members | 2,421 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 2055
In article <2xgVg.787$rS.2 21@fed1read05>,
jmcgill <jm*****@email. arizona.eduwrot e:
>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.eduwrit es:
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_Keit h) 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.eduwrot e:
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.eduwrot e:
>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.eduwrot e:
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
1657
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 was defined first as a 5-element vector, and then was increased dramatically but the corresponding contiguous area has already been occupied by other objects? Maybe sounds stupid to you gurus, but it does confuse me:( Thanks. ...
2
1788
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 paticular record and a bit concered about the size of record. (I assuming that an array of 1000 ints will be smaller than 1000 records of table dailyclose ( varchar Symbol, int beta ). Is this a fair assumption ? (I'm not actually concerned with seek...
8
2377
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 double-check. I heard that ISO 14882 standard did not guarantee this. Has this changed? Any pointers will be appreciated. Thanks, Ravi.
3
1515
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
5121
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 using clr:/pure syntax
22
3083
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
2611
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
4549
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
2117
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 asking for comments on it. In particular: Are there any gotchas that I have overlooked? Are there any suggestions for improvements? Is there a generally available superior packages to do the same thing with the same general licensing? ...
0
8428
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
8341
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
8754
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
8542
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
8630
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
6181
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
5650
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();...
2
1984
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1740
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.