brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.6 KiB · c9a2a64 Raw
58 lines · plain
1.. title:: clang-tidy - bugprone-misplaced-operator-in-strlen-in-alloc2 3bugprone-misplaced-operator-in-strlen-in-alloc4==============================================5 6Finds cases where ``1`` is added to the string in the argument to ``strlen()``,7``strnlen()``, ``strnlen_s()``, ``wcslen()``, ``wcsnlen()``, and8``wcsnlen_s()`` instead of the result and the value is used as an argument to a9memory allocation function (``malloc()``, ``calloc()``, ``realloc()``,10``alloca()``) or the ``new[]`` operator in `C++`. The check detects error cases11even if one of these functions (except the ``new[]`` operator) is called by a12constant function pointer. Cases where ``1`` is added both to the parameter and13the result of the ``strlen()``-like function are ignored, as are cases where14the whole addition is surrounded by extra parentheses.15 16`C` example code:17 18.. code-block:: c19 20    void bad_malloc(char *str) {21      char *c = (char*) malloc(strlen(str + 1));22    }23 24 25The suggested fix is to add ``1`` to the return value of ``strlen()`` and not26to its argument. In the example above the fix would be27 28.. code-block:: c29 30      char *c = (char*) malloc(strlen(str) + 1);31 32 33`C++` example code:34 35.. code-block:: c++36 37    void bad_new(char *str) {38      char *c = new char[strlen(str + 1)];39    }40 41 42As in the `C` code with the ``malloc()`` function, the suggested fix is to43add ``1`` to the return value of ``strlen()`` and not to its argument. In the44example above the fix would be45 46.. code-block:: c++47 48      char *c = new char[strlen(str) + 1];49 50 51Example for silencing the diagnostic:52 53.. code-block:: c54 55    void bad_malloc(char *str) {56      char *c = (char*) malloc(strlen((str + 1)));57    }58