Question

I am not good at English but I hope you understand what I say :) I'm trying to improve my skill.

Ok, I had some code like below:

int main()
{
    int x;
    int* p = new int();

    cin >> x; // waitting for user enter a integer number
    // BUT, what if the user force closes the program?

    cout << "The instructions from this to the end are not going to be run!" << endl;
    delete p;
    //..

    return 0;
}

The memory which was allocated by p pointer will never be disposed.

Do we have a solution for this problem?

THANKS :)

Updated: Is it a memory leak?

Was it helpful?

Solution

Any modern OS will manage it and clean up the whole memory that allocated by a process after closing it

Don't worry about that. You must worry about the memory when your program is running.

When your code is running. Avoid using bare pointers, try to use smart pointers if you need pointers.

OTHER TIPS

The operating system will take care of this. It will free all memory (and also other resources like sockets) that were allocated by the program after the program finishes.

A SIGKILL, or the Windows equivalent of that, will close the program without cleanup occurring. The OS will reclaim memory and resources like file descriptors/file handles. There's very little you can do about that; "hard kill" signals exist as a last resort for programs that will not terminate voluntarily.

Some other "soft kill" signals can be caught and handled appropriately.

If you take Windows, for instance, then closing the console window will force-close your application.

All memory and OS-handles that your program has allocated will be freed by the OS itself, so that is not something that you need to worry about. One cannot 'protect' against all possible forced application terminations.

You should make a program that under normal conditions leaks no memories, and if using exceptions then does not leak when an exception is thrown.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top