Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
int *getNum()
{
int wholeNum;
cout << "Enter a number: ";
cin >> wholeNum;
return &wholeNum;
}


What I have tried:

C++
int getNum()
{
int wholeNum;
cout << "Enter a number: ";
cin >> wholeNum;
return &wholeNum;
}
Posted
Updated 18-Mar-23 20:34pm
v2

The problem is that at return line, wholenum is deallocated and do not exist anumore.
So the address your return contain unknown value.
The easiest solution is to return the int directly
C++
int getNum()
{
int wholeNum;
cout << "Enter a number: ";
cin >> wholeNum;
return &wholeNum;
return wholeNum;
}
 
Share this answer
 
To add to what Patrice has rightly said, this is called a "dangling refernece" and it is called because there are different "types" of memory:
1) Global memory that are allocated at compile time when you create a variable outside any function.
2) Heap memory that you allocate while your code is running using new or malloc / calloc
3) Stack memory which is dynamically used when you call functions.

When you call a function, it's return address is pushed on the stack, and all the variables that function uses are allocated space on the stack as well.
When the function returns, the memory for the variables is released, the return address is popped off the stack, and the code continues from there.
When you call another function, the same thing happens and the same stack memory space is overwritten with the new function info - this is what makes recursion work: each time you call a function recursively, new space is used on the stack for it's variables and return address.

But if you return the address of a stack based variable, that's a problem - because the address is valid, but the content will be overwritten the next time you call any function! Hence the "Dangling reference": it's real, it works, but it doesn't really exist any more!

As Patrice says, return the actual number rather than a pointer to it - that means that a copy of the value is returned and there is no dangling reference.

If you need to return something "bigger" than an integer or float, then you need to allocate the space on the heap and return that pointer - but that complicates things as you are responsible for freeing that memory when you are done with it or your program will develop a memory leak and eventually crash as a result.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900