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:
Is this true?
And are there other cases where I have to worry about memory releasing?
Failing to free memory can result in the exhaustion of system memory resources, which can lead to a denial-of-service attack.
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.
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).
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.
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 memory and lifetime management to suitable container or manager classes, most notably std::vector
and std::unique_ptr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With