f



why I got this answer?

Hi all.
  I write a small program. But I can't understand the result of it. here is my code:
-----------------------------------------
#include <stdio.h>

int* foo(int n)
{
    int *p = &n;
    return p;
}

int f(int m)
{
    int n = 1;
    return 999;
}

int main(int argc, char *argv[])
{
	int num = 1;
	int *p = foo(num);
	int q = f(999);
	printf("[%d]\n[%d]\n", *p, q);
}
-----------------------------------------
output:
[999]
[999]
Why *p is 999?
Then I changed my code:
-----------------------------------------
#include <stdio.h>

int* foo(int n)
{
    int *p = &n;
    return p;
}

int f()
{
    int n = 1;
    return 999;
}

int main(int argc, char *argv[])
{
	int num = 1;
	int *p = foo(num);
	int q = f();
	printf("[%d]\n[%d]\n", *p, q);
}
------------------------------------
output:
[1]
[999]
Why *p is 1? I can't understand why.

--
Thanks,
Madper Xie.
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
UTF
2/26/2013 4:51:39 PM
comp.lang.c.moderated 1019 articles. 1 followers. Post Follow

3 Replies
321 Views

Similar Articles

[PageSpeed] 42

On Tue, 26 Feb 2013 10:51:39 -0600 (CST), ??? <bbboson@gmail.com>
wrote:

>Hi all.
>  I write a small program. But I can't understand the result of it. here is my code:
>-----------------------------------------
>#include <stdio.h>
>
>int* foo(int n)

n is a variable which exists only while foo is executing.

>{
>    int *p = &n;

p points to n.

>    return p;

The value in p is returned to the calling function.  foo terminates
and all of its local variables cease to exist, particularly n.  Since
n longer exists, the value that was returned to the calling function
becomes, by definition, indeterminant..

>}
>
>int f(int m)
>{
>    int n = 1;
>    return 999;
>}
>
>int main(int argc, char *argv[])
>{
>	int num = 1;
>	int *p = foo(num);

As explained above, the value returned by foo is indeterminant.

>	int q = f(999);
>	printf("[%d]\n[%d]\n", *p, q);

Here you dereference p.  Since its value is indeterminant, this
invokes undefined behavior.

>}
>-----------------------------------------
>output:
>[999]
>[999]
>Why *p is 999?

With undefined behavior, any response is possible and all responses
are equaly correct and incorrect..

As a practical matter, let us assume that local variables are placed
on the stack that starts at 0x1000.
   1 - In main, num is created at 0x1000 and initialized to 1.
   2 - In main, p is created at 0x1004 and foo is called.
   3 - In foo, n is created at 0x1008 and set to 1.
   4 - In foo, p is created at 0x100c and initialized to 0x1008.
   5 - foo returns 0x1008 (which is stored in p at 0x1004), its
variables are destroyed, and the stack pointer is reset to 0x1008.
   6 - In main, q is created at 0x1008 and f is called.
   7 - In f, m is created at 0x100c and set to 999.
   8 - In f, n is created at 0x1010 and set to 1.
   9 - f returns 999 (which is stored in q at 0x1008), its variables
are destroyed, and the stack pointer is rest to 0x100c.
   10 - In main, p contains 0x1008 and that address is dereferenced to
produce an int.  Since 0x1008 happens to be the address of q, *p
evaluates to 999.

>Then I changed my code:
>-----------------------------------------
>#include <stdio.h>
>
>int* foo(int n)
>{
>    int *p = &n;
>    return p;
>}
>
>int f()
>{
>    int n = 1;
>    return 999;
>}
>
>int main(int argc, char *argv[])
>{
>	int num = 1;
>	int *p = foo(num);
>	int q = f();
>	printf("[%d]\n[%d]\n", *p, q);
>}
>------------------------------------
>output:
>[1]
>[999]
>Why *p is 1? I can't understand why.

You should rerun your tests with all optimizations turned off.  

-- 
Remove del for email
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
Barry
3/11/2013 11:25:40 PM
Am 26.02.2013 17:51, schrieb 谢成骏:
> Hi all.
>    I write a small program. But I can't understand the result of it. here is my code:
> -----------------------------------------
> #include<stdio.h>
>
> int* foo(int n)
> {
>      int *p =&n;
>      return p;

Here you take the address of the formal parameter "n", but this argument 
goes out of scope as soon as the function returns, so the result is 
undefined.



> }
>
> int f(int m)
> {
>      int n = 1;

This "n" has also local scope, and in particular is distinct from the 
formal parameter of "foo". As this initialization does not cause any 
effect, the compiler can even remove it (and might do so when 
optimization is enabled).

>      return 999;
> }
>
> int main(int argc, char *argv[])
> {
> 	int num = 1;
> 	int *p = foo(num);
> 	int q = f(999);
> 	printf("[%d]\n[%d]\n", *p, q);
> }
> -----------------------------------------
> output:
> [999]
> [999]
> Why *p is 999?

It could also be any other value.

> Then I changed my code:
> -----------------------------------------
> #include<stdio.h>
>
> int* foo(int n)
> {
>      int *p =&n;

Same problem.

>      return p;
> }
>
> int f()
> {
>      int n = 1;

Again, a statement without observable effects.

>      return 999;
> }
>
> int main(int argc, char *argv[])
> {
> 	int num = 1;
> 	int *p = foo(num);
> 	int q = f();
> 	printf("[%d]\n[%d]\n", *p, q);
> }
> ------------------------------------
> output:
> [1]
> [999]
> Why *p is 1? I can't understand why.

Same as above. *p could be anything. Actually, it would not even 
surprise me if the code would crash if you would assign to *p.

Greetings,
	Thomas
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
Thomas
3/11/2013 11:25:44 PM
On 2013-02-26, 谢成骏 <bbboson@gmail.com> wrote:
> Hi all.
>   I write a small program. But I can't understand the result of it. here is my code:
> -----------------------------------------
> #include <stdio.h>
>
> int* foo(int n)
> {
>     int *p = &n;
>     return p;
> }

n 'evaporates' after you hit the return
the value returned in p points to where n used to be.

> output:
> [999]
> [999]
> Why *p is 999?

999 got put where n used to be.

-- 
⚂⚃ 100% natural
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
Jasen
3/11/2013 11:25:47 PM
Reply:

Similar Artilces:

Better C/C++ Than C/C++?
I am looking for a good systems programming language that can be used instead of C/C++. My qualifications for the language are: * mature compiler(s) that produce native-code binaries (for Windows) * open source - preferable, but not 100% necessary Thanks, Kevin "Kevin Albrecht" <kevin@albrecht.net> writes: > I am looking for a good systems programming language > that can be used instead of C/C++. My qualifications > for the language are: > > * mature compiler(s) that produce native-code > binaries (for Windows) Ocaml, D, cyclone, Eiffel, Beta >...

jython and C-c C-c
How do I get C-c C-c to work with jython? I have the jpython command set to jython, and I can start the interpreter with C-C ! and then use C-c C-c, but this is rather frustrating. If I try to use C-c C-c without first starting the interpreter in another window I get wrong type argument: sequencep, jpython Thanks, Dave Cook ...

If you Got Questions? I bet We got Answers
http://ugotquestions.blogspot.com/ - Find out anything ! Leisure.201@gmail.com said the following on 4/28/2007 12:51 PM: > http://ugotquestions.blogspot.com/ - Find out anything ! It won't tell me what I want to know, you might want to work on it some. My question was simple: How do I dynamically insert a script node into any and all blonde nymphomaniacs webpages to mesmerize them into coming to my remote island? -- Randy Chance Favors The Prepared Mind comp.lang.javascript FAQ - http://jibbering.com/faq/index.html Javascript Best Practices - http://www.JavascriptToolbox.com/bes...

If you Got Questions? I bet We got Answers
http://ugotquestions.blogspot.com/ - Find out anything ! ...

If you Got Questions? I bet We got Answers
http://ugotquestions.blogspot.com/ - Find out anything ! ...

C as a Subset of C++ (or C++ as a superset of C)
Isn't it a lame use of human time and effort to maintain completely separate C and C++ standards? As in the words of Betty White about Facebook: "It seems like an incredible waste of time". Why don't the two standards groups get together and agree on a common specification for the ground which both standards cover? There would still be two separate standards, but they'd both be exactly the same for the common ground. The common ground document could be referred to by both standards instead of being maintained by both groups in individual efforts resulting in...

C/C++ in matlab and matlab in C/C++ ?
Is it possible to read C/C++ code in matlab and the other way around too? Hi, as long as C or C++ are written in text files you can edit them in the matlab editor. To see the special character of C or C++ coding language, in the editor go to menus: file>preferences>Edito/Debugger>language and on popup "Language" select "C/C++". This does not allow you to run the C/C++ code, just to view it i nicer way... regards, chris saneman <asdfsdf@asd.com> wrote in message <frl846 $f8i$2@news.net.uni-c.dk>... > Is it possible to read C/C...

c------->c++ and c++------>c
We can write c program in turbo c++ editor.But reverse is not true why? i.e The program will not compile if u write c++ program in turbo c editor vim wrote: > We can write c program in turbo c++ editor.But reverse is not true why? > i.e The program will not compile if u write c++ program in turbo c > editor This isn't about C; this is about some editor. Why the fircone should /we/ know? Ask in a relevant group. [And /why/, in an editor specialised to some specific programming languages, would you expect it to compile a /different/ one? Would you expect turbo perl to compi...

C/C++ in MATALB or MATLAB in C/C++?
Hi I've been asking on the net how to use MEX properly so that I can use C/C++ in MATLAB, but information is not forthcoming. There seems to be a lot on using MATLAB in C/C++ but not the other way around. I understand Mathworks is trying very hard to sell the Matlab Compiler, but even so, why is it SO hard to get information about MEX? Or is it that I've missed something very fundamental, meaning that I'm struggling over something that is actually quite easy? Any thoughts and info would be great. Thanks BullDog BullDog wrote: > Hi > > I've been asking on the net ...

slime C-c C-c annoyance
Does anyone have a good workaround for this problem other than: just be careful! When I've compiled a large package and slime has given me a *slime-compilation* buffer, I like to work through this buffer issue by issue, fixing the errors, warnings, etc. But If I ever press C-c C-c in the editor window while fixing an error, slime destroys the *(slime-compilation* buffer with the compilation output of C-c C-c. Jim Newton <jimka.issy@gmail.com> writes: > Does anyone have a good workaround for this problem other than: just be careful! > > When I've compiled a ...

C, C++ and C# Forums
Throne Software has opened up C, C++ and C# Forums at: http://www.thronesoftware.com/forum/ Join us! Throne Software wrote: > Throne Software has opened up C, C++ and C# Forums at: > > http://www.thronesoftware.com/forum/ For all of your forums newsgroups already exist. > Join us! Why? Don't see any reason to support your marketing. ...

C, C++ and C# Forums
Throne Software has opened up C, C++ and C# Forums at: http://www.thronesoftware.com/forum/ Join us! In article <1120963701.862698.160260@g14g2000cwa.googlegroups.com>, Throne Software <mail@thronesoftware.com> writes >Throne Software has opened up C, C++ and C# Forums at: > >http://www.thronesoftware.com/forum/ > >Join us! Why? The beauty of news groups is that they come to me I don't have to go to them. Also all the people who have been around a while know what they are doing and are here. I noticed that there are some C and C++ Forums on another system...

C,, C++, Java, C#
I come from C,C++,Java and C#. What can SmallTalk do for me and for what cost? Regarding the Squeak thing, it's interesting though confusing. Is it an IDE? Why are the menus so wacky? "DM McGowan II" <nospam@nospam.net> wrote in message news:PLednX2vnLd11IncRVn-rA@comcast.com... > I come from C,C++,Java and C#. What can SmallTalk do for me ...? Ask not what Smalltalk can do for, but what can you do with Smalltalk. :-) In very few words, it significantly reduces time to market, while enhancig the development experience. This is because: 1. It...

C, C++ and C# Forums
Throne Software has opened up C, C++ and C# Forums at: http://www.thronesoftware.com/forum/ Join us! ...

c,c++,obj-c
Of the 3 languages titled in this post is c++ older than obj-c ? Would someone experienced in C be able to dive right into C++ rather than obj-c ? Java is out for me now except applet programming I think I'm going to go with just C and C++. Bill Bill Cunningham wrote: > Of the 3 languages titled in this post is c++ older than obj-c ? Why does that matter? Do you want to use an old language? Try Fortran or LISP. > Would > someone experienced in C be able to dive right into C++ rather than > obj-c ? Not quite dive in, at least not into the OO parts of C++. ...

Web resources about - why I got this answer? - comp.lang.c.moderated

Answer - Wikipedia
Generally, an answer is a reply to a question or is a solution, a retaliation, or a response that is relevant to the said question. In law, an ...

Call Button: An Answer To Facebook’s Mobile Ad Woes?
Ever since Facebook went public last year, the company has been looking for ways to monetize, especially on mobile . Jason Spievak, CEO of RingRevenue ...

OBAMACARE: What should WE do about Chief Justice John Roberts? My answer just might surprise you. - Facebook ...
David Osborne hat eine Notiz mit dem Titel OBAMACARE: What should WE do about Chief Justice John Roberts? My answer just might surprise you. ...

What Facebook search can answer
... thoughts on how the social network might approach search. Zuckerberg raised an interesting concept when he spoke about Facebook offering “answers” ...

Oppositelock - Why do my nostrils whisper to me? Answer: Because you're weird.
Why do my nostrils whisper to me? Answer: Because you're weird.

faroo_p2p: My answer to As of August 2012, what is the current state of the art in distributed hash tables ...
faroo_p2p: My answer to As of August 2012, what is the current state of the art in distributed hash tables? http://t.

Answers: Not just for developers anymore - Twitter Blogs
Answers grows to over five billion sessions per day.

Your Most Important Career Question - And How To Answer It
... ourselves some fundamental questions. I believe there is no career question that is more Your Most Important Career Question - And How To Answer ...

Labor demands answers on government frontbencher Stuart Robert's China trip
Scandal is threatening to engulf another Turnbull government minister, with Labor accusing Stuart Robert of potentially breaching ministerial ...

Well, we know the answer to this question.
Oh... I was going to link to something that, on closer look, just isn't good enough for you. Seriously, you'd have more fun speculating about ...

Resources last updated: 2/8/2016 10:09:22 PM