0
void f() {
int *ptr = new int;
// is the following line necessary?
delete ptr;
}

int main() {
f();
return 0;
}

Do i have to free the allocated memory in the function f or is it freed automatically because there is no reference to that memory anymore?

  • 2
    Yes (to avoid a leak) though to tell you the truth, if you just want something that's lifetime is bound to a specific scope, then you should most of the time be avoiding dynamic allocation. Dynamic allocation can be slow, it might allocate memory somewhere totally different in physical memory leading to slow access, and you have to manage it yourself. – George Jun 03 '20 at 23:52
  • 1
    `new` and `delete` should be considered advanced topics in C++ because while they're easy to use, it turns out they're really hard to use correctly once the programs you write start getting complicated. They should only be used in edge cases where a automatic allocation, a container, or a smart pointer does not fit. – user4581301 Jun 03 '20 at 23:59
  • Instead of `int *ptr = new int;` do `auto ptr = std::make_unique(0);` and then you don't have to manage the destruction yourself. – Eljay Jun 04 '20 at 00:19
  • For small programs that terminate (i.e. a finite lifetime), it is allowed (in many environments) to rely on "process-exit" cleanup (of the OS, not part of C++) to free the allocated memory. So, you do not _have_ to. It is not freed 'automatically'. I suspect the "process-exit" cleanup would also apply (i.e. when your program terminates by exception or abort or kill, etc.) For embedded software which generally does not terminate, or only terminate for power bounce, you probably should free them, because a repeating 'leak' will eventually crash your system. – 2785528 Jun 04 '20 at 00:21

2 Answers2

4

Do i need to free allocated memory from local pointers in c++?

If you want to avoid memory leaks - and you should want to - then you should dellacate everything that you allocate. There should be one delete for each allocating new.

or is it freed automatically

Dynamic allocations are not freed automatically.

because there is no reference to that memory anymore?

Whether memory is referenced is irrelevant in regard to whether its memory is deallocated. If dynamic memory is not referenced by anything, then the memory has been leaked. C++ does not have garbage collection.

Some classes do allocate memory and free that allocation in their destructor. This idiom is called RAII (look up the initialism to learn more). A pointer is not a class and it has no destructor. Ending of the lifetime of a pointer has no effect on the pointed object.


You should avoid using bare owning pointers. I recommend to use RAII containers or smart pointers (which are not actually pointers, but classes) to manage the memory instead. Standard library provides those out of the box. Also, avoid dynamic allocation when it isn't needed.

There is hardly ever a need to use new and delete directly, and they should be avoided when possible.

eerorika
  • 181,943
  • 10
  • 144
  • 256
  • 2
    To elaborate a bit further on smart pointers, if you replace the line `int *ptr = new int;` with `auto ptr = std::make_unique();` then you _don't_ have to delete anything because the `unique_ptr` destructor will do this for you automatically. (You need to `#include ` to use this.) – cdhowie Jun 03 '20 at 23:51
1

C++ does not have a garbage collector. If you allocate memory dynamically using the new operator, you have to free it using the delete operator.

So, the function will introduce a memory leak if the allocated memory:

int *ptr = new int;

Is not freed before exiting the function.

You can avoid such a problem using smart pointers, for example std::unique_ptr, eg:

#include <memory>

//...

void f() {
    std::unique_ptr<int> ptr = std::make_unique<int>();
    //...
} 
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
  • 1
    I'd still advise against using `new` even as part of a `unique_ptr` construction. This can be a problem when there are [multiple temporaries](https://stackoverflow.com/q/22571202/501250) involved and something throws. `std::make_unique` should be used to construct _all_ `unique_ptr` objects unless you are transferring ownership of an existing allocation into a new `unique_ptr` instance. It's much easier to get things right with `std::make_unique` and there are no downsides (that I can see). – cdhowie Jun 04 '20 at 00:08
  • @cdhowie The problem is that for example C++ 11 does not have std::make_unique. – Vlad from Moscow Jun 04 '20 at 00:22
  • 1
    @VladfromMoscow `std::make_unique()` can be written manually in C++11: [How to implement make_unique function in C++11?](https://stackoverflow.com/questions/17902405/). – Remy Lebeau Jun 04 '20 at 00:25
  • @RemyLebeau I doubt that a beginner can implement himself make_unique. – Vlad from Moscow Jun 04 '20 at 00:26
  • 1
    @VladfromMoscow he can just copy/paste it from the linked questions :-) – Remy Lebeau Jun 04 '20 at 00:26