Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be avoided to write memory-leak-safe code using STL?

I've used STL for quite a while now, but mostly to implement algorithms for the sake of it, other than the occasional vector in other code.

Before I start using it more, I wanted to know what the common mistakes people make when using STL are -- in particular, are there any things I should watch for when using STL templates to keep my code safe from memory leaks?

like image 650
Vanwaril Avatar asked Feb 18 '11 16:02

Vanwaril


People also ask

How can we avoid memory leak?

To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.

How do you stop a memory leak in C++?

The best way to avoid memory leaks in C++ is to have as few new/delete calls at the program level as possible – ideally NONE. Anything that requires dynamic memory should be buried inside an RAII object that releases the memory when it goes out of scope.

What is the main cause of memory leaks in applications?

Holding the references of the object and resources that are no longer needed is the main cause of the memory leaks in android applications. As it is known that the memory for the particular object is allocated within the heap and the object point to certain resources using some object reference.

Which of the following is an example of a memory leak?

The memory leak would occur if the floor number requested is the same floor that the elevator is on; the condition for releasing the memory would be skipped. Each time this case occurs, more memory is leaked. Cases like this would not usually have any immediate effects.


2 Answers

There are a lot of bottlenecks in using STL effectively, if you want to know more I'd suggest the book "Effective STL" by S.Meyers.

like image 141
grzkv Avatar answered Nov 15 '22 05:11

grzkv


When you store raw pointers to dynamically allocated objects in containers, containers won't manage their memory.

vector<FooBar*> vec;
vec.push_back(new FooBar); //your responsibility to free them

To make it more memory-leak proof use containers of smart pointers, or special-purpose pointer containers, as in Boost: pointer containers

Particularly considering that if an exception gets thrown, execution might not reach the manual clean-up code (unless painful efforts are made).

like image 37
UncleBens Avatar answered Nov 15 '22 07:11

UncleBens