Is it safe and predictable to reuse pointers after freeing the data they point to?
For example:
char* fileNames[] = { "words.txt", "moreWords.txt" };
char** words = NULL;
int* wordsCount = NULL;
for ( i = 0; i < 2; ++i ) {
data = fopen( fileNames[i], "r" );
words = readWords( data );
wordsCount = countWords( words );
free( wordsCount );
for ( j = 0; words[j]; ++j )
free( words[j] );
free( words );
fclose( data );
}
*error checking omitted
I am running the code and it appears to run (no warnings, errors, or memory problems) but I am wondering if this is safe and predictable to use in most environments (specifically in a typical Linux environment)?
If this isn't 'safe and predictable', what is the best way to accomplish the same operations on two different files, short of creating two times the amount of pointers, etc?
EDIT: I am asking if it is okay to reusing a pointer variable after freeing what it pointed to. I understand you should not use a pointer value after freeing. Assume the code works perfectly (it works as intended, memory is being freed correctly and such). I cannot change the spec. for this assignment.
Thanks!
When you declare a pointer it will be allocated for it a memory location. That location can be reassigned. If you reassign it after having assigned it a value with a malloc() call and before to free() it, this is a memory leak. After free() you can reassign it and no leak will happen, do not forget to free() it again.
It is better to reuse variables in terms of memory. But be careful you don't need the value in a variable before reusing it. Other than that, you shouldn't use always the variable. It is important to keep a clean and readable code.
Freeing a variable deallocates its memory. While the location that variable was at may still hold the old value, it may not. It is bad practice to use a variable that has been freed, and often leads to bugs and crashes.
Use-After-Free (UAF) is a vulnerability related to incorrect use of dynamic memory during program operation. If after freeing a memory location, a program does not clear the pointer to that memory, an attacker can use the error to hack the program.
What you're doing is fine: because, after you release a pointer, you're reinitializing it before you reuse it.
If the question is "is it safe to reuse a pointer value after freeing it" then the answer is "no".
If the question is "is it safe to reuse a pointer variable after freeing its value" then the answer is "yes, provided you reinitialize it to a (new) valid value before you reuse it".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With