Hi all:
I have declared a pointer as following:
char *stringPtr = NULL;
stringPtr = malloc(10);
After I finish with it,
free(stringPtr);
Do I need to put up another line:
stringPtr = NULL;
Thank you
Printable View
Hi all:
I have declared a pointer as following:
char *stringPtr = NULL;
stringPtr = malloc(10);
After I finish with it,
free(stringPtr);
Do I need to put up another line:
stringPtr = NULL;
Thank you
You don't need to. Though, if you free stringPtr, stringPtr is NOT set to NULL. So if you want also to set it to NULL and not just free the memory (which helps in some occasions) then you can add the line strPtr = NULL
Basically, the rule is "if the pointer is still available, then set it to NULL". If the pointer is local to a function, and you have a free at the very end of the function, then you don't need to set the pointer to NULL.
If you often find yourself writing:
you could make a function:Code:free(ptr);
ptr = NULL;
Edit: Re-reading the subject of the post: You do not "free" a pointer. You free the memory associate to that pointer. [Of course, you can have a pointer to pointer situation where the first level pointer is also allocated, in which case you'd have to do (at least) two free operations, but it still applies that the original pointer is not freed].Code:freeAndNull(void **ptr)
{
free(*ptr);
*ptr = NULL;
}
char *p;
p = malloc(...);
...
freeAndNull(&p);
...
--
Mats