In the book "Secure Coding in C and C++", the author mentions three different ways to manage strings across a project.
Caller allocates, caller frees (C99, OpenBSD, C11 Annex K)
Callee allocates, caller frees (ISO/IEC TR 24731-2)
Callee allocates, callee frees (C++ std::basic_string)
Then he mentions, "The third memory management mode, in which the callee both allocates and frees storage, is the most secure of the three solutions but is available only in C++."
Why is the third mode most secure?
First of all, the statement that the third method is only available in C++ is nonsense.
All three methods are possible in both C and C++.
Regarding the "secure" part, it depends on what you're doing. If you're writing a self-contained string class (like eg. std::basic_string), the third method is likely the best because the class self-manages it's own memory completely.
A string class relying on memory allocations/deletions in main (or any other external part) is an invitation to forget the necessary allocations when using strings. (=high probability of bugs)
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