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()
{
开发者_StackOverflow 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 x
and y
are placed at the same memory location (or register), since their usage lifetimes don't overlap. There's no need to keep x
around after first line, so the compiler is allowed to discard it. If you were to use x
later 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 i
is indeed in range.
You are returning pointers into the same container. Both x
and y
are pointers into elements of array
. Any change that is performed in array
will be visible through both pointers as they refer to the same region of memory.
If you need different results you will have to dynamically allocate new objects (whether explictly or implicitly with the use of std::string
or std::vector
--recommended).
The value of the pointer (the memory address) of x is not changing. The memory which x is pointing to is being modified.
The entire program has undefined behavior because i is uninitialized. There's nothing else to explain. You're lucky it didn't decide to format your hard drive instead.
精彩评论