Windows and Linux.
When I allocate memory in my C program, good coding wants me to free the memory before the end of my program.
Assume the following:
int main (int argc, char *argv[]) {
char *f_name;
FILE *i_file;
f_name = malloc(some_amount);
// put something in f_name */
i_file = fopen(f_name, "r");
if (i_file == NULL) {
perror("Error opening file.");
exit(EXIT_FAILURE);
}
free(f_name);
return EXIT_SUCCESS;
}
If the program terminates before I call "free", will the OS recover any un-freed memory when the program exits? Or will I just nibble away from my 3Gb or so available memory until a system restart?
Thanks, Mark.
You don't have to worry about it on popular OSes like Windows and Linux.
Virtual memory ceases to exist when the process terminates. So it's not possible for it to leak after a process terminates.
Physical memory always belongs to the OS to allocate as it pleases, whether or not your process is still running. (Unless you lock your allocations, in which case it ceases to be locked when the corresponding virtual memory mapping is destroyed which happens on process termination anyway.)
There are a few resources that are not cleaned up (like some types of shared memory) but that's pretty exotic.
When you call malloc
, typically just backing store (essentially RAM+swap) is reserved and a virtual memory mapping (which is essentially free) is created. When you first write to that virtual memory mapping, physical pages of memory (RAM) are mapped into it to "back" it. That RAM always belongs to the OS to use as it pleases and the OS will re-use the RAM for other purposes if it deems that wise.
When a process terminates, its address space ceases to exist. That means any virtual memory mappings or reservations go away. Unshared physical pages will have their use count drop to zero when the virtual memory mapping goes away, rendering those pages of physical memory free.
It's worth understanding this in detail because you can easily draw the wrong conclusions about edge cases if you don't understand what's going on under the hood. Also, this will give you a framework to plug concepts such as file mappings, memory overcommit, and shared memory into.