returning a reference fom a local (within function) variable from a function back to the caller
my Q is quite similar to these, but not exactly the same to:
Returning const reference to local variable from a function
Returning function-local variable as reference
I have a bit of code that is used to parse an xml file. what's basically happening is that a local variable is passed by reference OUT of the function using the return statement. To be more precise:
ezxml_t ezxml_parse_fd(int 开发者_运维知识库fd){
ezxml_root_t root;
//DO STUFF
return &root->xml;
}
the caller is the following
ezxml_t xml = ezxml_parse_fd(fd);
Well, the thing compiles and works (gcc)... but I have always known that a local variables are destroyed once their scope no longer exists... i'm confused
The local variable is not "passed out by reference", because that would mean return &root;
, which is not what your code says.
Rather, a pointer to some other, unrelated variable, which you didn't care to show us, is returned, and we should assume that the code was correctly written so that that pointer points to some dynamically allocated memory which will remain valid.
Once the function returns, function stack is unwound & references to function-local variables are invalid. You may get away with it for now, but don't rely on it!
Why not pass an output parameter to the function to store the value? Maybe, on these lines:
void ezxml_parse_fd(int fd, ezxml_t *parse_value)
{
ezxml_root_t root;
//DO STUFF
*parse_value = &root->xml;
return;
}
...
ezxml_t xml;
ezxml_parse_fd(fd, &xml);
If you are using gcc
there is a good chance that you might have seen a warning message "warning: function returns address of local variable" Please do pay attention to compiler warning! It is only trying to help you (most of the times) :)
Hope this helps!
yes, the local variables are destroyed already, but your reference points to the place in memory that hold last assigned value. The place where your variable was placed. And it will work in most cases in the single threaded environment for simple types. But when you allocate on the stack some object with destructor, the destructor will be called just when the execution of block (in your case -- function) will be finished. So outside the function you have a reference to destroyed object. Shortly: don't do this :-)
In C - that is probably very wrong. Please tell us what ezxml_t is and what root->xml is.
My guess is that ezxml_t is automatically casted to by the pointer to root->xml that you return.
精彩评论