Lost Refference ?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

int *bar(int *p) {
    return p;
}
int* foo(int n) {
    return bar(&n);
}
int main() {
    int *p1 = foo(1);
    int *p2 = foo(2);
    printf("%d, %d\n", *p1, *p2);
}


Output : 2 2

Can you please explain me every step, what is really happening here because I am very confused.
Last edited on
Try to answer these questions.

In
1
2
3
4
5
6
7
int *bar(int *p) {
    return p;
}

int* foo(int n) {
    return bar(&n);
}


a. When does the life-time of n (object of type int) start?
b. When does it end?
c. The function returns the address of an int; does the object at that address exist after the function returns?
a .when calling foo(1) , the int n gets integer 1 assigned DIRECTLY to it ( I guess no need to copy "1" here , correct me if I'm wrong)
b,c. lifetime ends after ";" of the return statement , thus we give a copy of address of the local n variable ( which its value will be garbage).

Nevertheless I still don't get it. I expected to receive some garbage value but not 2 times "2"
Last edited on
> lifetime ends after ";" of the return statement

Yes.


> thus we give a copy of address of the local n variable ( which its value will be garbage).

We can talk about the 'value' of an int if an only if the int in question exists. n had a value which it held till the end of its life-time; there is no int to hold that old value once the lifetime of n is over.


> I expected to receive some garbage value but not 2 times "2"

What you have got is undefined behavior.

Or talking in terms of garbage values, 2 2 is one of the many possible values that garbage could have.
Thank you I got it.

But this kind of undefined beahviour seems a little bit strange to me , you can try messing with the values in the parameters of the called functions , you'll get "nice" output.
Yes, getting a "nice", repeatable output from undefined behaviour with a particular C++ implementation (and a particular combination of compiler options) is quite possible.

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message)

However, that does not make the code correct; it is not behaviour that we should be depending on.
Last edited on
Topic archived. No new replies allowed.