Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If in C++ objects with automatic storage are not destroyed by calling exit, what happens with this objects after leaving the program?

On this site (cplusplus.com) I read that objects with automatic storage are not destroyed by calling exit(). Does it mean that there will be a memory leak? I know that when you reach the end of the automatic variable's scope they will be destroyed, but in this case does it mean that we don't reach the end of scope and simply leave the program?


I'm curious what will happen with memory in this example that I found in forums:

C++ code

#include <cstdlib>
#include <iostream>

struct C
{
    ~C()
    {
        std::cout<<"X"<<std::endl;
    }
};

void f()
{
    C c;
    exit(1);
}

int main()
{
    f();
}

Here the "X" was not outputted so destructor was not called. Can we say then that it is a memory leak?


EDIT:

Thank you for your responses. But I want to clarify something else. Assuming that the operating system will not release memory after completion of the program, does this mean that after the exit() call the object with automatic storage will cause a memory leak (because it will not be destroyed)? Or it may only occur when allocating memory from heap using, e.g., operator new?

Maybe I formulated the question not too clear, but I would like to know whether objects with automatic storage destroyed in any case, even if the program is not reached before the end of the block and interrupted by exit() call.

like image 278
Dagua Avatar asked Jan 05 '23 23:01

Dagua


2 Answers

Normal memory allocation cannot leak, because when the process exits all of its memory pages are cleaned up. However, objects that clean up process-independent external resources (like files) in their destructor can leak them, for example:

class TempFile {
public:
   TempFile() { /* create a file on disk */ }
   ~TempFile() { /* delete the file from disk */ }
}
void foo() {
   TempFile tf;
   exit(0);
}
like image 121
Wheezil Avatar answered Jan 25 '23 19:01

Wheezil


It's a memory leak in general; a modern OS will clean it though.

I would suggest to read the accepted answer below because we need to know what you meant by a "memory leak":

Still Reachable Leak detected by Valgrind

like image 40
lllllllllll Avatar answered Jan 25 '23 21:01

lllllllllll