Well this is always true, so I guess that means there's no such thing as memory leaks in C. Checkmate garbage collectors.
Well this is always true, so I guess that means there's no such thing as memory leaks in C. Checkmate garbage collectors.
An actual memory leak is when the amount of memory program allocates grows with runtime while the amount of data the program is processing remains the same.
To illustrate the difference, I wrote two quick programs.
This one has memory that the OS can recover:
#include <stdlib.h>
int main(void) {
char *a = malloc(10);
return 0;
}
This one has memory that the OS cannot recover: #include <stdlib.h>
int main(void) {
char *a = malloc(10);
a = malloc(10);
return 0;
}No, that's not how it works....
/sarcasm
When a process allocates memory, the kernel doesn't give it a physical memory address. It gives it a virtual address, which, when accessed, will be mapped to some physical address. The kernel has to keep track of which virtual addresses map to which physical addresses for each process, and it stores these mappings in a data structure called a "page table". At all times, the kernel knows what memory segments are in use by a given process.
So, when a process exits, the kernel can just look at its page table to see what memory had been allocated to it. Provided that no other processes shared the same memory, it can free it.