When interrupting a process, does a memory leak occur

exitmemoryprocess

Lets say I created a program in c/c++, where I manually allocated some variables. Then while running the program, I send an interrupt signal (Ctrl-C). Are those variables freed from memory, or will they take up space until the system shuts down?

Also, what if I just created integers that weren't manually allocated, do those variable reside, or do they get deleted immediately.

I'm thinking allocated variables will remain, and regular variables will get deleted (because of the stack). If that is the case, is there any way to free the allocated variables from memory after the program has stopped?

Just curious. 🙂

Best Answer

Processes are managed by the kernel. The kernel doesn't care how the programmer allocates variables. All it knows is that certain blocks of memory belong to the process. The C runtime matches C memory management features to kernel features: automatic variables go into a memory block called “stack” and dynamic storage (malloc and friends) go into a memory block called “heap”. The process calls system calls such as sbrk and mmap to obtain memory with a granularity of MMU pages. Inside those blocks, the runtime determines where to put automatic varibles and dynamically allocated objects.

When a process dies, the kernel updates its memory management table to record, for each MMU page, that it is no longer in use by the process. This takes place no matter how the process exits, whether of its own violition (by calling a system call) or not (killed by a signal). Pages that are no longer used by any process are marked as reusable.

It's generally good hygiene to free the dynamically allocated storage that you're no longer using, because you never know when a piece of code might be reused in a long-running program. But when a process dies, the operating system will release all of its resources: memory, open file, etc.

The only resources that the operating system won't clean up automatically are resources that are designed to have a global scope on the operating system, such as temporary files.

Related Question