开发者

Returning a local structure variable not dynamically allocated?

开发者 https://www.devze.com 2023-03-14 14:50 出处:网络
consider the following code:- struct mystruct { int data; struct mystruct *next; }; void myfunc () { struct mystruct s1;

consider the following code:-

struct mystruct {
    int data;
    struct mystruct *next;
};

void myfunc ()
{

 struct mystruct s1;
 s1开发者_如何转开发.data= 0;
 s1.next = NULL;
 myfunc2(&s1);
 ..
 ..
}

is it safe to pass the address of this local structure to other function. Will this local structure be available for use outside the function or will it be already freed ?


It is safe to pass the address of a local variable to another function. The variable's life time extends to the end of the block (function or compound statement) in which it is declared.

It is not safe to return the address of a local variable or save a pointer to it and use it after the declaring function has returned.


Your wording is awkward in the question.

You can pass it to other functions by adress. It'll still be in valid scope.

But you can't return it by adress (which you are not doing here) outside of the function in which you declared it.


It will be available in myfunc2, but only as long as myfunc has not returned.

If myfunc2 somehow remembers this pointer and tries to use it after myfunc has returned, unpredictable things will happen because the stack has already been restored and the pointer will point to whatever garbage is there.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号