简体   繁体   中英

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?

Here's an example using (int *) instead of my code's (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?

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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