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.