| 1 |
.. title:: clang-tidy - bugprone-suspicious-realloc-usage |
| 2 |
|
| 3 |
bugprone-suspicious-realloc-usage |
| 4 |
================================= |
| 5 |
|
| 6 |
This check finds usages of ``realloc`` where the return value is assigned to the |
| 7 |
same expression as passed to the first argument: |
| 8 |
``p = realloc(p, size);`` |
| 9 |
The problem with this construct is that if ``realloc`` fails it returns a |
| 10 |
null pointer but does not deallocate the original memory. If no other variable |
| 11 |
is pointing to it, the original memory block is not available any more for the |
| 12 |
program to use or free. In either case ``p = realloc(p, size);`` indicates bad |
| 13 |
coding style and can be replaced by ``q = realloc(p, size);``. |
| 14 |
|
| 15 |
The pointer expression (used at ``realloc``) can be a variable or a field member |
| 16 |
of a data structure, but can not contain function calls or unresolved types. |
| 17 |
|
| 18 |
In obvious cases when the pointer used at realloc is assigned to another |
| 19 |
variable before the ``realloc`` call, no warning is emitted. This happens only |
| 20 |
if a simple expression in form of ``q = p`` or ``void *q = p`` is found in the |
| 21 |
same function where ``p = realloc(p, ...)`` is found. The assignment has to be |
| 22 |
before the call to realloc (but otherwise at any place) in the same function. |
| 23 |
This suppression works only if ``p`` is a single variable. |
| 24 |
|
| 25 |
Examples: |
| 26 |
|
| 27 |
.. code-block:: c++ |
| 28 |
|
| 29 |
struct A { |
| 30 |
void *p; |
| 31 |
}; |
| 32 |
|
| 33 |
A &getA(); |
| 34 |
|
| 35 |
void foo(void *p, A *a, int new_size) { |
| 36 |
p = realloc(p, new_size); // warning: 'p' may be set to null if 'realloc' fails, which may result in a leak of the original buffer |
| 37 |
a->p = realloc(a->p, new_size); // warning: 'a->p' may be set to null if 'realloc' fails, which may result in a leak of the original buffer |
| 38 |
getA().p = realloc(getA().p, new_size); // no warning |
| 39 |
} |
| 40 |
|
| 41 |
void foo1(void *p, int new_size) { |
| 42 |
void *p1 = p; |
| 43 |
p = realloc(p, new_size); // no warning |
| 44 |
} |