-3

I have this code:

int foo() {
    int r = 100;
    int *s = &r;
    return *s;
}

void main() {
    cout << foo();
    system("pause");
}

I thought the result should be junk value, not 100.

But when I test it in Windows 8.1 and Mac OS X, the result is 100.

Can someone explain it to me?

user975326
  • 657
  • 1
  • 7
  • 22
Forrest
  • 723
  • 2
  • 8
  • 24
  • It seems fairly straightforward to me that it should return 100. why do you think it should be junk? – Fabio Sep 04 '15 at 17:14
  • Because when `return *s` , it will return the memory of `r` , but when `foo` was finished , the memory of `r` would be deleted . So I think the result should be junk value – Forrest Sep 04 '15 at 17:18
  • 2
    It doesn't return the memory, doing `return *s` instead of `return s` means that you're returning the value at the address instead of the address. Your function returns `int`, not `int*`. – porglezomp Sep 04 '15 at 17:20
  • ya, I mean it will return the value of `r` , but when foo was finished , the address/memory of `r` would be released, so why it still returns 100 there? – Forrest Sep 04 '15 at 17:27
  • 1
    @DươngAnhKhoa At return the return value is passed (constructed) before local variables go out of scope. –  Sep 04 '15 at 17:31
  • ok,thanks This is a problem that my teacher had asked me today – Forrest Sep 04 '15 at 17:34

2 Answers2

2

No, there shouldn't be a "junk value". s points to an object within the same scope, both s and r are destroyed when the function exits. You safely dereference s before r is destroyed.

Also void main() is incorrect.

  • `void main()` should instead be `int main()` Most compilers will return an error when you use void instead of int. – Quiver Sep 04 '15 at 17:30
  • To add to my previous comment. The reason you don't use `void main()` is because it is the standard to use `int main()` - You can read more about it here: http://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main – Quiver Sep 04 '15 at 17:38
2

That's because *s is simply the value that the pointer is pointing to.

if you have:

int a = 2;
int *b = &a;
printf("%d\n", *b);
a = 3;
printf("%d", *b);

it's gonna print:

2
3

but if you have:

int a = 2;
int b = 3;
int *c = &b;
printf("%d\n", a);
a = *c;
printf("%d\n", a);
*c = 5;
printf("%d\n", a);

it's gonna print

2
3
3

and not

2
3
5

because when you do a = *c; it just copies the value of c into a, but establishes no further relation between c and a, which means you can change c or the value that it's pointing to whatever you want, and a is gonna continue holding that value that c had when you did that assignment. They're 2 different spaces in memory and what a = *c does is merely copy the value that c is pointing to to a

What I mean by all that is that when you return *s you're not returning the address to the memory s is pointing to, but the value that it contains

Fabio
  • 3,015
  • 2
  • 29
  • 49