Question about malloc - free and exit prog.
I am writing a tiny basic-like language, for each statement the user types in (or read from a save file) some memory is malloc'ed.
Before my program ends do I need to free each one? Is there a call to free all of them at once? Does Linux recover the memory if I don't free it? I will also need to clear all these malloc'd bits if the user clears the program space (to enter a new program), so a "clear every malloc" would still be nice. Thanks! |
If i remember correctly when a program ends its address space is marked as avalible and can be reused by another program so in essence yes its freed at program termination. But still its a good idea to free all memory you used for good mesure.
|
When you exit all the allocated memory will be automatically free'd for you, otherwise you have to free it all individually. Which isn't that hard, you can keep track of the allocated memory by constructing a linked list of the variables that you have allocated.
An alternative way to tackle it would be to run the user program as a child process. That way it would be isolated from the rest of the program and so any "crash" situation wouldn't actually crash the parent process. |
It's going to be difficult (that is, impossible) to find memory leaks if you don't free your memory after you've finished with it. For every function that allocates memory you should have a cleanup function that frees it again. In between, you keep track of the pointers using some sort of data structure (list/hash table/etc), as graemef suggests.
|
A good way(for me) to make sure that I've freed everything I've malloc is to grep my sources and make sure that every ?alloc has an associated free.
For this thing, I like the idea of an array of pointers for each procedure. Free'em when the procedure finishes. Assuming your program is going to support some form of functions and not just one big process. |
Quote:
The process would benefit from it's own pseudo heap if it was going to allow globals. |
Yes - "exit()" will absolutely clean up everything you've malloc'ed.
And yes, although it's OK to rely on "exit()" for small, toy programs, it's arguably poor form. You should get into the habit of "cleaning up after yourself" so that you won't foget to do it when it counts (like writing a server daemon, for example ;-)). |
All times are GMT -5. The time now is 03:50 PM. |