-4

I have two pointer have same address. If I free one. I should not use 2nd one. because its free memory But I might be using that in next code. Also if I free one I cant free second .Plz give me solution with example.

4

1 回答 1

1

The idea is that when you free one of the two pointers, then set both to NULL. Also, it is a good programming practice to always test that a pointer is set before using it.

 char *ptr1 = malloc(80);

 char *ptr2 = ptr1;

 free(ptr2);
 ptr1 = ptr2 = NULL;
 // other stuff happens here, and if the code doesn't "know"
 // that ptr1 is set correctly then...
 if (ptr1 != NULL)
 {  // etc.

 }

Hope this is what you were asking, and hope it helps. Good Luck with your future coding endeavors.

于 2013-08-16T05:37:58.310 回答