Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I have to free memory?

Tags:

c++

memory

I learned C# and now I'm learning C++. The whole point of releasing a memory is new for me, and I want to know when I need to worry about memory releasing and when I don't.

From what I understand, the only case I have to worry about the release of memory, is when I used new operator, so I should to release the memory by using delete.
But in these cases there is no need to release the memory:

  • Class variables (Members), or static variables.
  • Local variables in function.
  • STL family (string, list, vector, etc.).

Is this true?
And are there other cases where I have to worry about memory releasing?

like image 330
user1544067 Avatar asked Jan 31 '13 12:01

user1544067


People also ask

Why do you need to free memory?

Failing to free memory can result in the exhaustion of system memory resources, which can lead to a denial-of-service attack.

When should I use free () in C?

free() function in C should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. free() function only frees the memory from the heap and it does not call the destructor. To destroy the allocated memory and call the destructor we can use the delete() operator in C.

What happens if you dont free memory?

If free() is not used in a program the memory allocated using malloc() will be de-allocated after completion of the execution of the program (included program execution time is relatively small and the program ends normally).

Do I need to free memory before exit?

You do not need to free your memory before exit. During the termination of the process the kernel also deletes the memory mappings which were associated with that process. So everything is "freed" implicit by the kernel.


1 Answers

You basically got it right: You need to balance new with delete, new[] with delete[], and malloc with free.

Well-written C++ will contain almost none of those, since you leave the responsibiltiy for dynamic memo­ry and lifetime management to suitable container or manager classes, most notably std::vector and std::unique_ptr.

like image 148
Kerrek SB Avatar answered Oct 04 '22 09:10

Kerrek SB