0
  1. I don’t know what is wrong with the following code.
  2. It tells address of local variable returned.
#include <iostream>
using namespace std;

int *myfunc(int *ptrB);

int main() {
    int *a, b;
    cout << "give b :" << endl;
    cin >> b;
    a = myfunc(&b);
    cout << "a is :" << *a << endl;
    return 0;
}

int *myfunc(int *ptrB) {
    int a; 
    a= (*ptrB) * (*ptrB);
    *ptrB = a;
    return &a;
}
ib.
  • 27,830
  • 11
  • 80
  • 100
  • 5
    Why do you return a pointer to the variable instead of returning it by value? – JVApen Sep 12 '20 at 17:24
  • 3
    `int a;` in `myfunc` is destroyed as soon as the function returns, so the pointer to it (that was returned) is invalid and can't be used for anything useful. – HolyBlackCat Sep 12 '20 at 17:27
  • Look up what is [undefined behaviour](https://en.cppreference.com/w/cpp/language/ub) in C++. Because, that's a local variable you are returning, so the pointer is most probably dangling – kesarling He-Him Sep 12 '20 at 17:32
  • The actual address of `a` returned could be different everytime, so we can't tell you what the value will be. I suspect that it will be an address on the stack. – quamrana Sep 12 '20 at 17:32
  • 1
    Does this answer your question? [What is a dangling pointer?](https://stackoverflow.com/questions/17997228/what-is-a-dangling-pointer) – kesarling He-Him Sep 12 '20 at 17:38
  • At least for C, (and I suspect C++) even the equivalent C code of `cout << "address a is :" << a << endl;` is UB. – chux - Reinstate Monica Sep 12 '20 at 17:44

2 Answers2

3

"I don't know what is wrong." - What is wrong is that you are returning the address of a local variable that ceases to exist once the function returns, so that address points to a dead object and trying to use it is UB.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • As a minor, maybe insignificant addition. Someone took the time to write this severely convoluted piece of code, well knowing it would be invalid code. – Captain Giraffe Sep 13 '20 at 00:19
0

When you do anything with a pointer that is returned by a function, like dereference it, which is a typical thing to do with a pointer, you need to know that the object that your pointer points to exists. However, the pointer you return points to an object that exists in scope of the returning function; after the function has returned, the function scope no longer exists and the object goes down with it. It is like holding an address of a house that has been demolished and hoping you can spend the night there.