xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/no-malloc.rst (revision 0f1f1d45c9f77bf5d8e5dce32551b7c78772b8a6)
1.. title:: clang-tidy - cppcoreguidelines-no-malloc
2
3cppcoreguidelines-no-malloc
4===========================
5
6This check handles C-Style memory management using ``malloc()``, ``realloc()``,
7``calloc()`` and ``free()``. It warns about its use and tries to suggest the use
8of an appropriate RAII object.
9Furthermore, it can be configured to check against a user-specified list of functions
10that are used for memory management (e.g. ``posix_memalign()``).
11
12This check implements `R.10
13<https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-mallocfree>`_
14from the C++ Core Guidelines.
15
16There is no attempt made to provide fix-it hints, since manual resource
17management isn't easily transformed automatically into RAII.
18
19.. code-block:: c++
20
21  // Warns each of the following lines.
22  // Containers like std::vector or std::string should be used.
23  char* some_string = (char*) malloc(sizeof(char) * 20);
24  char* some_string = (char*) realloc(sizeof(char) * 30);
25  free(some_string);
26
27  int* int_array = (int*) calloc(30, sizeof(int));
28
29  // Rather use a smartpointer or stack variable.
30  struct some_struct* s = (struct some_struct*) malloc(sizeof(struct some_struct));
31
32Options
33-------
34
35.. option:: Allocations
36
37   Semicolon-separated list of fully qualified names of memory allocation functions.
38   Defaults to ``::malloc;::calloc``.
39
40.. option:: Deallocations
41
42   Semicolon-separated list of fully qualified names of memory allocation functions.
43   Defaults to ``::free``.
44
45.. option:: Reallocations
46
47   Semicolon-separated list of fully qualified names of memory allocation functions.
48   Defaults to ``::realloc``.
49