user14056942
user14056942

Reputation:

Leaking memory when calling exit(0)

I read before that:

When you exit a C++ program by calling the exit() function, the object destructors are not run. This can result in Valgrind reporting memory leaks.

But what if I'm waiting for user input and if it's exit then I want to exit the program, how may I do that?

I am scanning input in a function called by another one called by main. Like this:

void main()
{
    func1();
}

void func1()
{
    func2();
}

void func2()
{
    std::string str;
    getline(std::cin, str);
    if (str=="exit") exit(0);
}

Upvotes: 0

Views: 708

Answers (2)

catnip
catnip

Reputation: 25388

According to cppreference:

Returning from the the main function, either by a return statement or by reaching the end of the function, executes exit(), passing the argument of the return statement (or ​0​ if implicit return was used) as exit_code.

In other words, calling exit is the same as returning from main (or falling off the end), which in turn calls the destructors of any statically allocated objects before the program finally quits.

That said, std::exit offers the appropriate guarantees, so that's the one to use.

Live demo


Edit: If you want to ensure that variables allocated at local scope are destroyed (see discussion) then you could throw a custom exception at the point where you want to exit the program and catch it in main, e.g.

class ExitProgramException {};

void foo ()
{
    ...
    if (exit_program)
    {
        ExitProgramException e;
        throw e;
    }
}

void bar ()
{
    foo ();
}

int main ()
{
    try
    {
        bar ();
    }
    catch (const ExitProgramException& e)
    {
    }
}

This should ensure that the stack is unwound correctly.

Live demo

Upvotes: 4

CiaPan
CiaPan

Reputation: 9570

Just do if (str=="exit") return;

Upvotes: -1

Related Questions