0

In C++ after the program is executed does the heap memory gets deallocated manually or it is done by compiler automatically

Rashmi
  • 1
  • 1
  • 4
    *Everything* gets deallocated when the program exits, by the operating system, not the compiler. – user207421 Sep 10 '21 at 05:17
  • 1
    No C++ doesn't deallocate memory allocated with "new " or malloc automatically. These are called memory leaks and they MUST be avoided. The operating system acts as a safeguard and will ensure that all memory is made available again for other processes after shutdown. To avoid memory leaks try writing code that uses the RAII principle, (https://en.cppreference.com/w/cpp/language/raii). In C++11 and later just try to avoid using new/delete altogether (e.g. std::make_unique, std::make_shared ) – Pepijn Kramer Sep 10 '21 at 05:18
  • 3
    If your program runs atop an operating system, the operating system will clean up. But there's always the possibility that you'll run the program out of memory before that happens if you don't clean up no longer used memory as you go . – user4581301 Sep 10 '21 at 05:24
  • 2
    *In C++ do we deallocate the heap memory manually or it is done by compiler automatically* -- So are you asking whether C++, as the program is running, automatically deallocates the memory, or when the program shuts down, whether the memory is deallocated? – PaulMcKenzie Sep 10 '21 at 05:25
  • when the program shuts down – Rashmi Sep 10 '21 at 05:29
  • 1
    @Rashmi: The answer is the same as it is in any language, making this a duplicate of [When you exit a C application, is the malloc-ed memory automatically freed?](https://stackoverflow.com/q/2213627/364696). `malloc` is just the C mechanism for getting heap memory, but the answer is identical for `new`. – ShadowRanger Sep 10 '21 at 05:38

0 Answers0