Can we use a pointer freed earlier?

I have a question regarding free () in C.

Suppose I have a pointer to some structure (say node * ptr) .. after freeing it can initialize it to NULL and point to some new location using malloc () or realloc ()?

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 this valid or will cause a problem. The reason I used realloc instead of malloc is because all my realloc () calls are in a loop (so instead of the second argument to sizeof (node) it's n * sizeof (node)), where n continues incrementing ... and the last place in this resulting array is written with new data), where the memory pointed to by ptr continues to increase until the loop ends, and at that moment I don't need the data in the memory pointed to by ptr, so I think that it’s best to free him. Now all this is embedded in another (external) loop.

Many thanks for your help

+4
source share
3 answers

This is normal - you are not really reusing a pointer, but only a variable containing a pointer.

+9
source

ptr does not remember that it was once assigned a value, and reusing it again if it was assigned. NULL is no different from using it for the first time.

And since realloc() acts like malloc() when it passed a NULL pointer, it should work fine.

+7
source

You should not think of it as “freeing the pointer”, but freeing everything that the pointer points to. It is perfectly normal that a pointer points first to one object (which can then be freed), and then to another object.

+3
source

Source: https://habr.com/ru/post/1301344/


All Articles