-2

I have an application which should throw an exception if it encounters a situation. Application aborts, excepted behavior.

Address sanitizer is reporting memory leaks for this scenario. Should I consider fixing the memory leaks in this case (or) Should I not do it as the application is terminating anyways and the memory will be reclaimed by the OS anyway.

  • 3
    Probably the biggest benefit of C++ over some other languages (e.g. C) is the *destructor*. This features allows the [Resource Acquisition Is Initialisation](https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) pattern, specifically to avoid problems like this. By using objects on the stack to own memory, and release it in their destructors, you can safely clean up all resources in any path unwinding your stack (any combinations of throwing exceptions and `return`ing). Check out [`std::unique_ptr`](https://en.cppreference.com/w/cpp/memory/unique_ptr). – BoBTFish Jul 24 '18 at 06:34
  • 1
    Possible duplicate of [RAII and smart pointers in C++](https://stackoverflow.com/questions/395123/raii-and-smart-pointers-in-c) –  Jul 24 '18 at 06:39
  • @BoBTFish: This sounds like an unhandled exception (no `catch`). Ordinarily, destructors between `throw` and `catch` are executed, but that range is not defined for uncaught exceptions. – MSalters Jul 24 '18 at 09:05
  • 1
    As a rough guideline, your code code should avoid explicit memory allocation (i.e. operator `new` and variants) wherever possible (e.g. use a standard container rather than dynamically allocating an array). If it is necessary to explicitly use dynamic memory allocation, store the resultant pointer in an object with a destructor that will clean up properly if an exception is thrown. In that way, you don't need to worry about forgetting to deallocate memory if an exception is thrown. – Peter Jul 24 '18 at 09:31

1 Answers1

0

Yes, you should free memory manually, even though the program terminates. Imagine you or someone else chooses to add an exception handling strategy later on, because the program can recover from the error scenario. You want to be prepared for future changes, and techniques like RAII yield everything you need to accomplish that.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • 'My app has 30 threads with complex classes and susb-systems that cannot be easily deleted during a run, objects with OS calls/callbacks outstanding on them and memory/object pools where it is not possible to determine which thread is using what object at any instance' now how goes your suggestion? :) I mean, 'free memory manually' sounds good in a textboox, but in practice, it soon becomes a flock of albatross that you have to lug around when developing non-trivial apps:( – Martin James Jul 25 '18 at 07:21