473,698 Members | 2,873 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this correct..??

jt
#include <stdio.h>
void f();

int main()
{
long int i;
i=20;
f();
i = 10;
printf ("\n%d\n",i) ;
return 0;
}

void f()
{
int j=20;
*(&j+2)+=7;
}

I found this question in the internet. The output is 20. Even I didn’t
believe this till I executed this program.
The probable explanation will be:

&j refers to the address of j.
&j + 2 refers to the address next to j(since j is of type <int).
This may be place where the return address is stored.(i think the
return address is stored immediately after the variables).

That value is incremented by 7.
May be the assignment statement takes 7 bytes to be represented in the
macine language.
Therefore the assignment statement in the main(),<i=10wil l be
skipped.
So the value of "i" is never altered.
Is my explanation correct..??
Jun 27 '08 #1
6 1838
jt wrote:
#include <stdio.h>
void f();

int main()
{
long int i;
i=20;
f();
i = 10;
printf ("\n%d\n",i) ;
return 0;
}

void f()
{
int j=20;
*(&j+2)+=7;
}

I found this question in the internet. The output is 20.
The result is undefined. On my box, it is

Segmentation Fault (core dumped)

--
Ian Collins.
Jun 27 '08 #2
jt said:
#include <stdio.h>
void f();

int main()
{
long int i;
i=20;
f();
i = 10;
printf ("\n%d\n",i) ;
return 0;
}

void f()
{
int j=20;
*(&j+2)+=7;
}

I found this question in the internet. The output is 20. Even I didn?t
believe this till I executed this program.
You shouldn't have believed it then, either. &j is okay, but adding 2 to it
yields an invalid pointer value, and that means that the behaviour of the
program is undefined. The behaviour you observed is only one of a
brazillion possible outcomes.

<snip>
Is my explanation correct..??
I didn't read it. *The* correct explanation is that the program is broken
in a way that places no constraints on the output. Explaining one
arbitrary output doesn't actually explain the bug, and therefore can't
explain the program.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #3
jt wrote:
#include <stdio.h>
void f();

int main()
{
long int i;
i=20;
f();
i = 10;
printf ("\n%d\n",i) ;
return 0;
}

void f()
{
int j=20;
*(&j+2)+=7;
}

I found this question in the internet. The output is 20. Even I didn?t
believe this till I executed this program.
The probable explanation will be:
We recently had another post whose code is broken in a similar manner.
These tricks seem very cute, but the code exhibits undefined behaviour,
which means that any result is possible.
&j refers to the address of j.
Correct.
&j + 2 refers to the address next to j(since j is of type <int).
No. It is an address that is sizeof &j + 2 bytes past the address &j.
It's an invalid pointer value since it points at no legal object at
all. The address &j is legal because it points to j. The address &j+1
is legal, but may not be deferenced (This is a general rule in C: that
you may legally point to one element past an array but may not use that
address in a lvalue context), but the address &j+2 is completely
invalid. Even forming it invokes implementation defined behaviour, let
alone deferencing it.
This may be place where the return address is stored.(i think the
return address is stored immediately after the variables).
Pure speculation. On some machines the return address is stored on a
separate stack. Other systems it may or may not be stored at the
address that this program expects it to be.

If you want to do tricks like this then assembler is far better than C.
Almost everthing is defined in assembler. Once you know the platform's
assembler and the type of object code that your compiler generates,
then you might be in a position to translate your tricks into C without
hoping for the favour of the Gods of undefined behaviour.
That value is incremented by 7.
What if one some platform int is 16 bits while function return addresses
are 32 bits? Another potential problem.
May be the assignment statement takes 7 bytes to be represented in the
macine language.
Pure speculation. Easily defeated by compiler optimisations. What if
your friendly optimisng compiler observes that i is used only ever by
printf and that the first assignment to i is never used and decides to
emit a printf statement like this:

printf("\n%d\n" , 10L);

Observe that there is a printf format specifier mismatch in your
original code: another invocation of undefined behaviour.
Therefore the assignment statement in the main(),<i=10wil l be
skipped.
So the value of "i" is never altered.
Is my explanation correct..??
No. Your explanation is the purest of unfounded speculation one can
imagine. Your program is broken and the fact that it appears to do
something cute on one particular platform, under one particular
compiler, and under one set of compiler options doesn't mean that
anything meaningful is guaranteed in any other circumstance.

If you want to learn machine level architecture then I suggest that an
assembly language course is actually better than messing around with
highly non-portable C code. You can always come back to C with a new
understanding of how things work behind the scenes and be more
confident of exactly what happens when programs like these are run than
just speculating.

Jun 27 '08 #4
On Sat, 26 Apr 2008 21:20:40 -0700 (PDT), jt <ka**********@g mail.com>
wrote:
>#include <stdio.h>
void f();

int main()
{
long int i;
i=20;
f();
i = 10;
printf ("\n%d\n",i) ;
One undefined behavior: the argument corresponding to the %d is not an
int.
return 0;
}

void f()
{
int j=20;
*(&j+2)+=7;
A second undefined behavior: the expression &j+2 computes an address
that is beyond the end of j and not equal 1 beyond the end.

A third(?) undefined behavior: even &j+2 were to point to an int, its
value would be indeterminate and cannot be evaluated for the +=
operator.
>}

I found this question in the internet. The output is 20. Even I didn’t
believe this till I executed this program.
The probable explanation will be:

&j refers to the address of j.
&j + 2 refers to the address next to j(since j is of type <int).
This may be place where the return address is stored.(i think the
return address is stored immediately after the variables).

That value is incremented by 7.
May be the assignment statement takes 7 bytes to be represented in the
macine language.
Therefore the assignment statement in the main(),<i=10wil l be
skipped.
So the value of "i" is never altered.
Is my explanation correct..??
While the information may be true for your system, it is not correct.
The only correct statement is the program invokes undefined behavior.
Remove del for email
Jun 27 '08 #5
On 27 Apr 2008 at 4:20, jt wrote:
[snip]
&j refers to the address of j. &j + 2 refers to the address next to
j(since j is of type <int). This may be place where the return
address is stored.(i think the return address is stored immediately
after the variables).

That value is incremented by 7. May be the assignment statement takes
7 bytes to be represented in the macine language. Therefore the
assignment statement in the main(),<i=10wil l be skipped. So the
value of "i" is never altered.

Is my explanation correct..??
Your explanation is extremely plausible. Why don't you disassemble the
code produced by your compiler and check?

Jun 27 '08 #6
jt ha scritto:
*(&j+2)+=7;
My guess:
Bad pointer,
you are deferencing something that it is not initialized.
Jun 27 '08 #7

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

Similar topics

1
7760
by: Richard Golebiowski | last post by:
I have been trying to figure this out for quite some time and cannot find any examples in VB.Net or in VB that work correctly. I am working on an application where I want the user to be able to select a peinter and printer tray to print reports out. In Crystal Reports 8.5, I can select a printer and tray and it prints correctly. I did a test report that I use to tell me the value that Crystal Reports is using for the paper source. When I...
1
292
by: Richard Golebiowski | last post by:
I have been trying to figure this out for quite some time and cannot find any examples in VB.Net or in VB that work correctly. I am working on an application where I want the user to be able to select a peinter and printer tray to print reports out. In Crystal Reports 8.5, I can select a printer and tray and it prints correctly. I did a test report that I use to tell me the value that Crystal Reports is using for the paper source. When I...
2
4978
by: thisis | last post by:
Hi All, I need the PUBS.mdb for pulling images: PUBS.mdb must have the table: pub_info tbl_pub_info : has 3 fields Data_Type : ok Data_Type : ok
3
1730
lee123
by: lee123 | last post by:
I have a problem getting the correct to count +1 every time I get an answer right and the incorrect is the same. I have two lbl's named number1 and number2 which produces a Rnd# in each lbl. I have a txt box for the answer called useranswer. A button to check if the answer is right called btnanswer. I have just added two more lbl's for the correct named lblcorrect & the other is lblincorrect. How do I get this to count when the...
10
2203
by: onetruelove | last post by:
I want to creat a post like this blog: http://onlinetoefltest.blogspot.com/2007/08/level-c-lesson-1.html When you chose all the answers and click show answer a msg box will appear and tells how many answers are correct I view the blog source and copied all the code to my post but it didn't work when i click the show answer button in my post. Can any one help me with the code? Thanks in advance
0
8683
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
9170
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
9031
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
8904
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
8876
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
6531
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
5867
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
4372
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...
3
2007
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.