can we use a pointer freed earlier?
I have a question regarding free() in C.
Suppose I have a pointer to some struct (say node *ptr).. after freeing it can i Initialize it to NULL and make it point to some new location using malloc() or realloc()?
For Example:
node *ptr=NULL;
ptr=realloc(ptr,sizeof(node)); //works exactly like malloc
/* Do some operations on开发者_如何学JAVA ptr */
free(ptr);
ptr=NULL;
ptr=realloc(ptr,sizeof(node));
Is that valid, or will it create a problem. The reason I used realloc in place of malloc is because all my realloc() calls are in a loop (so instead of sizeof(node) in the second argument it is actually n*sizeof(node) where n keeps on incrementing... and the last location in this resultant array is written with new data) where the memory pointed to by ptr keeps on increasing until the loop ends, at which point I do not require the data in the memory pointed to by ptr, so I think it best to free it. Now, all this is nested in one more bigger(outer) loop.
Thanks a lot for your help
It is ok - you are not really reusing the pointer but just the variable holding the pointer.
ptr
doesn't remember that it was once assigned a value, and re-using it again if it was assigned NULL is no different from using it the first time around.
And since realloc()
acts like malloc()
when it's passed a NULL pointer, it should work just fine.
You should not thinking about it as "freeing the pointer", but freeing whatever the pointer points to. It's perfectly normal that a pointer points first to one object (which may then be freed), and then to another object.
精彩评论