0

Why does my pointer have a different value after I've dereferenced it in main vs when Ive dereferenced it within my own custom function?

It's probably something really simple but I can't figure it out. Here is the code below:

int *addNumbers(int a, int b);

int main()
{
    int no1 = 1;
    int no2 = 3;
    int no3 = 8;
    int *answer = &no3;

answer = addNumbers(no1, no2);
std::cout << answer << std::endl;
std::cout << *answer << std::endl;

/* Why does this second cout line not give the same 
answer as the second cout statement
 in the addNumbers function? */

}

int *addNumbers(int a, int b)
{
    int *resultPntr;
    int result = a+b;
    resultPntr = &result;
    std::cout << resultPntr << std::endl;
    std::cout << *resultPntr << std::endl;
    return resultPntr;
}

I thought dereferencing resultPntr and answer would give the same value??

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Oanh
  • 41
  • 4

3 Answers3

8

addNumbers() is trying to return a pointer pointing to local variable result, which will be destroyed when get out of the function. Then answer in main() is just a dangled pointer, dereferencing on it is UB, means anything is possible.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

You're returning a pointer to result that is a local variable in addNumbers. Local variable lives into his scope. So when you exit from addNumbers will be destroyed!

If you want to get the same result you need to do this:

int *addNumbers(int a, int b)
{
    int *resultPntr = new int;
    *resultPntr = a+b;
    std::cout << resultPntr << std::endl;
    std::cout << *resultPntr << std::endl;
    return resultPntr;
}

N.B. When you declare new variables with new, you need to delete it at last.

granmirupa
  • 2,780
  • 16
  • 27
1

This line in addNumbers() function:

int result = a+b;
resultPntr = &result;
std::cout << *resultPntr << std::endl;
...
return resultPntr;

Displays the value of the result variable which is a local variable. Since result is a local variable its scope is with in the function it is defined which means it will no longer be available when your function returns to main.

In main:

answer = addNumbers(no1, no2);
std::cout << *answer << std::endl;

Is trying to deference the returned pointer from addNumbers() function. The returned pointer contain a memory location that was once occupied by the result local variable in your addNumbers() function which is now destroyed,as a result of returning to main, and hence the result of such an operation is undefined and you can't relay on it to give you the value you get when you were inside addNumbers().

This is one good reason why you should not return a reference or pointer of a local variable from a function.

Biruk Abebe
  • 2,235
  • 1
  • 13
  • 24