How is dynamically allocated space freed when a program is interrupted using Ctrl-C?
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 开发者_JS百科System here? And how is it different from that in case Of C++, done using the new
operator?
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.)
By the way (in addition to Seth Carnegie said):
Using the routines in <signal.h>
you can catch the SIGINT
signal (interrupt) to handle Ctrl+C in any way, for example to clean up any important resources, not only the memory (like closing files, thus avoiding the loss of any buffered and not-yet-written content, or closing network connections gently).
The full explanation of _exit
is here:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/_Exit.html
The same things happen when a process terminates as a result of a fatal signal.
the memory is actually not "free()"d at all.
memory acquired by the operating system is page size (4kbytes of memory usually). whenever a process runs out of memory it acquires additional pages, these are the space malloc() actually uses. when a process terminates all pages are returned to the operating system making calling free actually unnecessary. if your programme is a server or similar every piece of memory that is never freed will only be returned when the programme is actually killed - making it every more memory hungry.
精彩评论