简体   繁体   English

返回一个没有动态分配的本地结构变量?

[英]Returning a local structure variable not dynamically allocated?

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. 它将在myfunc2中可用,但只有myfunc没有返回时才可用。

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. 如果myfunc2以某种方式记住这个指针并在myfunc返回后尝试使用它,那么将发生不可预测的事情,因为堆栈已经被恢复并且指针将指向那里的垃圾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM