[英]Returning pointer from function after being initialized to non-local pointer
I think what I'm doing is safe but I want to check with all you smart people first. 我认为我正在做的事很安全,但是我想先与所有聪明的人确认一下。
I know returning a pointer to a local variable from a function is bad! 我知道从函数返回指向局部变量的指针是不好的!
But what if a pointer is allocated outside of a function call and passed in as input. 但是,如果指针在函数调用之外分配并作为输入传递,该怎么办。 Then inside the function call a local pointer is made, initialized to the input pointer, used to set some
struct->members
, and then return
ed? 然后在函数内部调用本地指针,将其初始化为输入指针,用于设置一些
struct->members
,然后return
ed?
Here's an example using (int *)
instead of my code's (struct type_s *)
: 这是一个使用
(int *)
而不是我的代码(struct type_s *)
:
int *modify_p_x(int *p_x)
{
int *new_p_x = p_x;
*new_p_x = 100;
return new_p_x;
}
int main(int argc, char **argv)
{
int x = 42;
int *p_x = &x;
p_x = modify_p_x(p_x);
return 0;
}
Since new_p_x is
initialized using p_x
and p_x
has a lifetime irrespective of the modify_p_x
function call, does that make this code safe? 由于
new_p_x is
使用p_x
初始化的,并且p_x
的生命周期与调用modify_p_x
函数modify_p_x
,所以这使此代码安全吗?
Thanks. 谢谢。
There is nothing wrong with local pointers; 本地指针没有错。 the problem is with returning a pointer to a local thing .
问题在于返回指向本地事物的指针。 Recall why this is bad: when the function returns, the memory used by that thing can be re-used for other things.
回想一下为什么这样做很糟糕:当函数返回时,该东西使用的内存可以重新用于其他东西。
modify_p_x
is given a pointer to x
(allocated in main
), uses it to change x
, and returns that pointer, which main
then re-assigns to p_x
. modify_p_x
被赋予指向x
的指针(在main
分配),使用它来更改x
并返回该指针,然后main
将其重新分配给p_x
。 Except for how it is used, this is no different than if you were using int
s instead of pointers, and I don't think you ever worried about returning an int
variable. 除了如何使用它,这与使用
int
而不是指针没有什么不同,而且我认为您不必担心返回int
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.