开发者

can we use a pointer freed earlier?

开发者 https://www.devze.com 2022-12-20 09:41 出处:网络
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() o

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号