Given the following code:
#include <stdio.h>
int main()
{
int *p;
p = (int *)malloc(10 * sizeof(int));
while(1);
return 0;
}
When the above code is compiled and run, and is interrupted while in execution by pressing Ctrl+C, how is the memory allocated to p
freed? What is the role of the Operating System here? And how is it different from that in case Of C++, done using the new
operator?
In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.
If the process quits, a memory leak will NOT normally occur. Most of the memory you allocate will be freed on Ctrl+C. If you see memory usage not return to its prior level, it is almost certainly caused by buffered filesystem blocks.
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own.
Destructor is can be used to release the memory assigned to the object. It is called in the following conditions. We can again use pointers while dynamically allocating memory to objects.
When a process terminates, the operating system reclaims all the memory that the process was using.
The reason why people make a big deal out of memory leaks even when the OS reclaims the memory your app was using when it terminates is that usually non-trivial applications will run for a long time slowly gobbling up all the memory on the system. It's less of a problem for very short-lifetime programs. (But you can never tell when a one-liner will become a huge program, so don't have any memory leaks even in small programs.)
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