0

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 returned?

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 themodify_p_x function call, does that make this code safe?

Thanks.

3
  • This is no code review site! Did you experience any problems with that code? (looks ok to me). Note always enable compiler warnings. Commented Oct 22, 2015 at 17:46
  • Your original premise is already wrong. "I know returning local pointers from a function is bad"? Who told you that? There's noting inherently bad with "returning local pointers". In fact, it is completely irrelevant whether the pointer itself is local or not. The only thing that matters is how "local" is the object the pointer is pointing to. Commented Oct 22, 2015 at 18:06
  • Sorry, I meant to say returning a pointer to a local variable. After returning from the function the local variable does not exists anymore. Commented Oct 22, 2015 at 18:08

1 Answer 1

2

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 ints instead of pointers, and I don't think you ever worried about returning an int variable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.