简体   繁体   中英

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

没关系 - 你并没有真正重用指针而只是持有指针的变量。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM