Fred Tingaud 22b4470f2a
Modify CFamily rules: CPP-4080 Refresh and standardize CppCoreGuidelines references (#3514)
Update all links to C++ Core Guidelines to `e49158a`.

Refresh done using the following script and some manual edits:
db76e34e74/personal/fred-tingaud/rspec/refresh-cppcoreguidelines.py

When re-using this script, be mindful that:
 - it does not cover `shared_content`
 - it does not properly escape inline code in links (e.g., "[=]" or "`mutex`es")
 - it does not change `C++` to `{cpp}` in link titles.

Co-authored-by: Marco Borgeaud <marco.borgeaud@sonarsource.com>
2023-12-20 10:08:18 +01:00

53 lines
1.6 KiB
Plaintext

== Why is this an issue?
The ``++malloc++``, ``++realloc++``, ``++calloc++`` and ``++free++`` routines are used to dynamically allocate memory in the heap. But, in contrast to the ``++new++`` and ``++delete++`` operators introduced in {cpp}, they allocate raw memory, which is not type-safe, and they do not correctly invoke object constructors. Additionally, mixing them with ``++new++``/``++delete++`` results in undefined behavior.
Note that directly replacing those functions with ``++new++``/``++delete++`` is usually not a good idea (see S5025).
=== Noncompliant code example
[source,cpp]
----
string* pStringArray1 = static_cast<string*>(malloc(10 * sizeof(string))); // Noncompliant
Person *p = (Person*)malloc(sizeof(Person)); // Noncompliant
----
=== Compliant solution
[source,cpp]
----
std::array<string, 10> stringArray1 ; // Compliant, use std::vector instead if the size is dynamic
auto p1 = new Person("Bjarne"); // Compliant, but don't do that, prefer the version on next line
auto p2 = std::make_unique<Person>("Bjarne"); // Compliant
----
== Resources
* {cpp} Core Guidelines - https://github.com/isocpp/CppCoreGuidelines/blob/e49158a/CppCoreGuidelines.md#r10-avoid-malloc-and-free[R.10: Avoid `malloc()` and `free()`]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this use of "XXX".
'''
== Comments And Links
(visible only on this page)
=== on 6 Sep 2013, 14:11:09 Freddy Mallet wrote:
See \http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free
endif::env-github,rspecator-view[]