Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a valid function?

What happens to the reference in function parameter, if it gets destroyed when the function returns, then how const int *i is still a valid pointer?

const int* func(const int &x = 5)
{
    return &x;
}


int main()
{
    const int *i = func();
}
like image 371
user972473 Avatar asked Sep 21 '11 03:09

user972473


People also ask

What is a valid function?

The VALID function determines whether x , a reference to a scalar pictured value, has a value that is valid with respect to its picture specification. The result is a bit string of length one that indicates if the character-string value of x can be edited into the picture declared for x .

What are the conditions in which function is valid?

For something to be a function, you need one output for each input. You do not need vice versa. Your equation x2+y2=1 does not define x or y as a function of the other because (for example) if I give you an x there are 0 or 2 values for y that satisfy the equation.

What is not a function in math?

Vertical lines are not functions. The equations y = ± x and x 2 + y 2 = 9 are examples of non-functions because there is at least one -value with two or more -values.


2 Answers

§12.2/5:

"A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call."

That means as i is being initialized, it's getting the address of a temporary object that does exist at that point. As soon as i is initialized, however, the temporary object will be destroyed, and i will become just another dangling pointer.

As such, yes, the function is valid -- but with the surrounding code as you've written it, any code you added afterward that attempted to dereference i would give undefined behavior.

like image 182
Jerry Coffin Avatar answered Oct 21 '22 17:10

Jerry Coffin


Just because a pointer has a value doesn't mean it's a valid pointer.

In this case it holds an address which used to be that of x, and chances are that address still has the value 5, but it's not valid pointer and you can't count on that value being there.

like image 38
Matt Lacey Avatar answered Oct 21 '22 15:10

Matt Lacey