Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

void f(char* charPointer) { free(charPointer); }

Status
Not open for further replies.

Workarounder

Programmer
Joined
Nov 10, 2007
Messages
2
Location
BR
Hi!

I have a program and in this program I have to do a lot of close´s and free´s. The program is something like this:

int main(int argc, char** argv) {
FILE* pFile = NULL;
FILE* pFile2 = NULL;
char* pChar = NULL;

pChar = (char*)malloc(30);

/* and more lines of code... */

return finalizing(pFile, pFile2, pChar);
}

static void finalize(FILE* f1, FILE* f2, char* c) {
if (f1 != NULL) {
fclose(f1);
}

if (f2 != NULL) {
fclose(f2);
}

if (f1 != NULL) {
free(c);
}

return 0;
}

My question is: will I have problems if I use free() function in the finalize() function? I mean, do we have to use free() only in the same function where we use malloc()? In other words, I am using malloc in the main() function, but I am calling free() in the finalize(), so the memory will not be deallocated. Does that make sense?


Thanks.
 
Looks just fine.
You can allocate and free wherever you like so long as each malloc() eventually results in exactly one free()

Also, please use [code][/code] tags when posting code.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
You will have problems if you use finalize twice. All you're checking for is that it is NULL but after freeing, you are not setting it to NULL so if you call it again, it will try to free again. Best set the pointer to NULL after it has been freed or closed. Unfortunately, to do that to a FILE*, you have to send in a FILE** and dereference all the way.
 
Thank you! That´s what I was wanting to confirm!

;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top