Tag Archives: signal

Delete Dynamically Allocated Memory by Ctrl-C

Intro

In this post, I will share an example C/C++ code demonstrating a method to safely delete dynamically allocated memory when a user terminates the application by Ctrl-C.

Problem

First let’s review a code which includes a problem. The code dynamically allocate a memory for the variable a. The code has delete[] function, but the application cannot arrive there due to the infinite loop which is very common in may applications. If a user terminates the application with Ctrl-C, then the memory will be leaked.

#include <iostream>

int main(){
    signal(SIGINT, myInterruptHandler);

    double* a;
    a = new double [1000];

    std::cout << "press ctrl-c\n" ;
    while(1){  }

    delete[] a;
}

The figure below shows the execution results.

As you can see the, the free memory continuously is reduced every time after the termination of the application by Ctrl-C.

Solution by Using Signal

In Linux system, if a user press Ctrl-C, a signal is sent to the process from the OS. We can catch the signal and make a different routine. One example is as below:

#include <iostream>
#include <signal.h>

uint8_t loop_flag = 1;

void myInterruptHandler (int signum) {
    loop_flag = 0;
}

int main(){
    signal(SIGINT, myInterruptHandler);

    double* a;
    a = new double [1000];

    std::cout << "press ctrl-c\n" ;
    while(loop_flag){

    }

    delete[] a;
    std::cout << "\nelegantly terminated wihout memory leakage\n";
}

The result of the code above is shown in the figure below:

In contrast to the previous result, the memory is not leaked and elegantly terminated.

Download/Build of Source Code

You can download the source code at this link.

More topics to read

There is another function called “sigaction()”. It seems more robust and well -defined. But it seems to need more lines of codes. Thus, I decided to use signal. For the details, please read this post .

Reference