exit/abort functions and dynamically allocated memory

Hi,

If I use the "exit" function after catching an exception, will the "exit" function delete dynamically allocated memory itself, or must I perform this myself? Further, will exit call the destructors of any user defined objects?

Would these answers remain the same if "abort" were substituted for "exit" in the paragraph above?

Thanks...
(code below)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdexcept>
#include <iostream>
using namespace std;

int main () {
	double *ptr = new double [10];
	/*
		user-defined objects containing dynamically allocated memory
	*/

	try {
		logic_error logicErr("Logic error occurred. Programme has exited.");
		throw( logicErr );
	}
	catch (logic_error logicErr) {
	cout << logicErr.what() << endl;
	exit(1);
	}

	delete [] ptr;
	return 0;
}
When the program ends, OS will free all the memory anyway.

http://www.cplusplus.com/reference/clibrary/cstdlib/abort/
http://www.cplusplus.com/reference/clibrary/cstdlib/exit/

It doesn't state whether exit() calls any destructors so compile this:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

struct S{
   S(){ std::cout << "ctor\n"; }
   ~S(){ std::cout << "dtor\n"; }
};

int main(){
   S s;
   exit(0);
   return 0;
}
(it doesn't)
Many thanks hamsterman.
You really should use return rather than exit as I don't think destructors are called if you use exit.

In the example above, neither return or exit will release ptr. You'll need auto_ptr to manage correct release (with return).
Last edited on
However, I am pretty sure that exit() will run global destructors.
Topic archived. No new replies allowed.