-2

i already searched stackoverflow and read that exit() cause memory leak

so i thought i could not avoid memory leak when i use this code

class A
{
public:
    int* m_pM;
    A() { m_pM = new int(1); };
    ~A() { delete m_pM; };
public:
    void Exit() { exit(0); }
};
int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

    A a;
    a.Exit();
}

So I asked the professor to move on to this problem

but my professor said me to work it out.

i dont know what to do... maybe she didn't think much about this problem.

she just said dont cause memory leak.

is there any solution that i dont know? ( not use return only use exit())

as df
  • 11
  • 2
  • 2
    Please, provide a link for where you _read that exit() cause memory leak_. I would expect the opposite: Every possible memory leak will be gone after exiting the application (as the OS will release resources which were occupied by a process). The only exception I could imagine might be IPC facilities but I cannot see any in your exposed code. – Scheff's Cat Jun 01 '22 at 06:58
  • Why do you use `exit` in the first place? – The Dreams Wind Jun 01 '22 at 06:59
  • If you're concerned about leaking, why not just call `delete m_pM;` before `exit(0);`? – πάντα ῥεῖ Jun 01 '22 at 07:02
  • `she just said dont cause memory leak.` She is wright. There is no memory leak. Your `A` class instance is constructed on heap and when exit the program, it's destroyed and pointer `m_pM` is deleted in destructor. So, it's all good with your code – Alexey Jun 01 '22 at 07:17
  • 2
    @Alexey No, `A` isn't destroyed, and `m_Pm` isn't deleted. `exit(0)` is called before `A::~A()` can be called. However it does not matter, as the operating system releases all memory and everything else when you call `exit(0)`. – user207421 Jun 01 '22 at 07:21
  • @OP Just remove `A::exit()` and its call. You don't need it. – user207421 Jun 01 '22 at 07:52
  • @user207421 You are wright - `objects with automatic storage are not destroyed by calling exit` – Alexey Jun 01 '22 at 09:20
  • You might want to read this question on How to end C++ code (https://stackoverflow.com/questions/30250934/how-to-end-c-code). The answers there go into detail on the different options and their problems and benefits. – Frodyne Jun 01 '22 at 09:50

0 Answers0