0

I have a struct:

        struct Foo
        {
            int x;
            int  *ptr;
            void *ptr2;
        };

If I allocate memory for ptr using:

        ptr = malloc(sizeof(int));

and later I want to it to point it to something else that already has memory allocated for it, do I need to free ptr before doing:

        ptr = *other_variable;
user1224478
  • 345
  • 2
  • 5
  • 15

1 Answers1

1

If you don't free before losing the pointer, the free never happens and you leak memory. So yes, you should do that.

Also, you probably want ptr = &other_variable rather than *other_variable, unless other_variable is of type int **.

Tom Hunt
  • 916
  • 7
  • 21