Let's say I have the following C code:
int main () { int *p = malloc(10 * sizeof *p); *p = 42; return 0; //Exiting without freeing the allocated memory }
When I compile and execute that C program, ie after allocating some space in memory, will that memory I allocated be still allocated (ie basically taking up space) after I exit the application and the process terminates?
This will happen automatically. You do not need to write anything for this.
Most memory on most OSes however will be automatically reclaimed when the process exits.
Yes, all memory is returned.
No it doesn't clear. The malloc function will request a block of memory from the heap . You have to pass the pointer returned form malloc to the free function when is no longer needed which deallocates the memory so that it can be used for other purposes.
It depends on the operating system. The majority of modern (and all major) operating systems will free memory not freed by the program when it ends.
Relying on this is bad practice and it is better to free it explicitly. The issue isn't just that your code looks bad. You may decide you want to integrate your small program into a larger, long running one. Then a while later you have to spend hours tracking down memory leaks.
Relying on a feature of an operating system also makes the code less portable.
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