Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 System here? And how is it different from that in case Of C++, done using the new operator?

like image 469
4sh1sh Avatar asked Sep 01 '11 22:09

4sh1sh


People also ask

How is dynamic memory allocation done in C?

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.

Does Ctrl C free 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.

Which function can be used to release the dynamic allocated memory in C?

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

Which keyword is used to release the dynamically allocated memory?

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.


1 Answers

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

like image 129
Seth Carnegie Avatar answered Oct 29 '22 05:10

Seth Carnegie