We’re getting some funny behavior in the Visual Studio debugger with the following.
I’m not sure if it’s the code or some debugger weirdness (seen stuff like it before).
We are trying to return a pointer to an value in an array.
The weird behavior is that the value of x changes to equal y after func() is called a second time…at least, that’s what it appears in the debugger.
I suppose my question is, is this even legal/safe?
The pointers should be on the heap in main()’s scope right, so it should be fine?
char stuff[100];
char * func()
{
// i is random in the range
stuff[i] = 'a';
return &stuff[i];
}
main()
{
char * x = func();
char * y = func();
}
Are you debugging with a debug build? You often get surprising results like this if you debug a release build.
A debug build will force the compiler to put all variables on the stack, and keep them around for their entire scope, so you get the expected debug view. A release build might reuse the space for one variable once it’s never going to be used again, even if it is still in scope, and might keep short-lived variables in processor registers rather than on the stack.
In a release build, it’s likely that
xandyare placed at the same memory location (or register), since their usage lifetimes don’t overlap. There’s no need to keepxaround after first line, so the compiler is allowed to discard it. If you were to usexlater on in the function, then it would need its own space on the stack, so you would probably see it in the debugger as expected.And to answer your question: yes this is valid and correct, as long as
iis indeed in range.