0

If I created some objects in the heap during the execution of my program; And I know that all these objects will continue to be accessed until the very final lines of codes of main(); Then is it malpractice to not delete the objects in the heap? and is there any actual harm from that behavior?

trincot
  • 317,000
  • 35
  • 244
  • 286
Physician
  • 483
  • 2
  • 7
  • It will work just fine when you don't clean up. Until that dark rainy day when you need to diagnose a memory leak, then you get to regret it. It always rains some day. – Hans Passant Dec 04 '21 at 11:24

2 Answers2

0

It all depends on your application's logic. If possible, prefer using the stack. This way the cleanup is completely automatic and you don't need to worry about memory leaks.

If you do need to use the heap, then use smart pointers like shared_ptr, which will make sure you don't leak any memory (but remember to free them as soon as you don't need the memory anymore, otherwise they would live until the program finishes).

If you provide some more details on what your program does and what memory you are asking about we could give you a more specific advice.

D-FENS
  • 1,438
  • 8
  • 21
  • 1
    [`auto_ptr`](https://en.cppreference.com/w/cpp/memory/auto_ptr) is deprecated(C++11)/removed(C++17), superseded by [`std::unique_ptr`](https://en.cppreference.com/w/cpp/memory/unique_ptr) (C++11). – Jarod42 Dec 01 '21 at 09:30
  • 1
    `auto_ptr` is deprecated since C++11 and removed in C++17, you should use modern smart pointers like `unique_ptr` or `shared_ptr`. – Holt Dec 01 '21 at 09:31
  • Sorry, my bad. I meant shared_ptr! – D-FENS Dec 01 '21 at 09:41
0

It is a good general rule to delete the objects when they are not used anymore. However, when a process exits, all its heap memory is released.

Eric Marchand
  • 619
  • 3
  • 10
  • 5
    Memory leak might not be the sole issue, classes might have destructor with interesting side effects (save in DB, close some resources, ...). – Jarod42 Dec 01 '21 at 09:35