tags:

views:

42

answers:

2

Hello I have a class with a function that returns a pointer:

int* Maze::GetStart()
{
    int startNode = 1;

    return &startNode;
}

Will the value of startNode be erased after the function returns the pointer?

If I did this instead would the value be saved?

int Maze::GetStart()
{
    int startNode = 1;

    return startNode ;
}

main
{
    int* pStart = maze.GetStart();
}
+3  A: 

Will the value of startNode be erased after the function returns the pointer?

The variable startNode will cease to exist once the function GetStart() returns, so in that sense, yes.

But, your code opens up a huge opportunity for undefined behavior by returning addresses to things that will disappear once GetStart() returns. If the caller attempts to dereference the returned node*, anything can happen. Also, the code can't possibly compile as-is since you can't implicitly cast an int* to a node*.

However, if you're returning by value, then you should be fine:

int Maze::GetStart() 
{ 
    int startNode = 1; 
    return startNode; 
    // return 1; // Why not do this?
} 

int pStart = maze.GetStart(); // Get returned value as int, not pointer to int. 
In silico
Thanks I have updated my question based on your answer.
Arizona1911
Okay but I want the pointer to the returned value. Will my updated code point to the value 1?
Arizona1911
@Arizona1911: What do you mean by "a pointer to the returned value"? Why do you need to do that?
In silico
I would like to do this but in one line int start = maze.GetStart(); int* pStart =
Arizona1911
@Arizona1911: I have a feeling that a better solution exists for what you want to do. What are you really trying to do? Why are pointers so necessary?
In silico
I don't have a good reason to use pointers. I will rethink my approach. Thanks.
Arizona1911
A: 

Returning address of a variable allocated on stack does not make sense at all. The life time of the variable startNode gets over as soon as the function GetStart() returns. It does not matter if it is a free function or member function.

I think, in gcc/g++ there is a warning for this.

Based on the question edit:

If you want to modify the variable and save the modified state then it must be declared static. See static local variables.

ArunSaha