Reputation: 51
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.
Upvotes: 4
Views: 1057
Reputation: 513
According to C++98 §18.3/8
When exit
, only static objects are destroyed, and then atexit
handlers are executed, openning streams are flushed and closed, and files created by tmpfile
are removed. Local automatic objects are not destroyed.
http://en.cppreference.com/w/cpp/utility/program/exit
Stack is not unwound: destructors of variables with automatic storage duration are not called
#include <cstdlib>
#include <iostream>
struct C
{
C( const std::string &name ) :
m_name( name ) { }
~C()
{
std::cout<< m_name << " destructor" <<std::endl;
}
std::string m_name;
};
static C c1( "Static C" );
void f()
{
C c( "Local C" );
exit(1);
}
int main()
{
f();
}
Upvotes: 1
Reputation: 144
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
Upvotes: 1
Reputation: 3472
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);
}
Upvotes: 7
Reputation: 100186
All that is telling you is that the destructor is not called. Not that the memory leaks.
Upvotes: 0