brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.8 KiB · 9885d9c Raw
46 lines · plain
1.. title:: clang-tidy - bugprone-suspicious-realloc-usage2 3bugprone-suspicious-realloc-usage4=================================5 6This check finds usages of ``realloc`` where the return value is assigned to7the same expression as passed to the first argument:8``p = realloc(p, size);``9The problem with this construct is that if ``realloc`` fails it returns a10null pointer but does not deallocate the original memory. If no other variable11is pointing to it, the original memory block is not available any more for the12program to use or free. In either case ``p = realloc(p, size);`` indicates bad13coding style and can be replaced by ``q = realloc(p, size);``.14 15The pointer expression (used at ``realloc``) can be a variable or a field16member of a data structure, but can not contain function calls or unresolved17types.18 19In obvious cases when the pointer used at realloc is assigned to another20variable before the ``realloc`` call, no warning is emitted. This happens only21if a simple expression in form of ``q = p`` or ``void *q = p`` is found in the22same function where ``p = realloc(p, ...)`` is found. The assignment has to be23before the call to realloc (but otherwise at any place) in the same function.24This suppression works only if ``p`` is a single variable.25 26Examples:27 28.. code-block:: c++29 30  struct A {31    void *p;32  };33 34  A &getA();35 36  void foo(void *p, A *a, int new_size) {37    p = realloc(p, new_size); // warning: 'p' may be set to null if 'realloc' fails, which may result in a leak of the original buffer38    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 buffer39    getA().p = realloc(getA().p, new_size); // no warning40  }41 42  void foo1(void *p, int new_size) {43    void *p1 = p;44    p = realloc(p, new_size); // no warning45  }46