How is dynamically allocated space freed when a program is interrupted using Ctrl-C?

前端 未结 4 850
遇见更好的自我
遇见更好的自我 2020-12-17 21:12

Given the following code:

#include 

int main()
{
    int *p;
    p = (int *)malloc(10 * sizeof(int));

    while(1);
    return 0;
}
<         


        
相关标签:
4条回答
  • 2020-12-17 21:25

    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.)

    0 讨论(0)
  • 2020-12-17 21:30

    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.

    0 讨论(0)
  • 2020-12-17 21:38

    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).

    0 讨论(0)
  • 2020-12-17 21:43

    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.

    0 讨论(0)
提交回复
热议问题