1.. title:: clang-tidy - bugprone-misplaced-operator-in-strlen-in-alloc 2 3bugprone-misplaced-operator-in-strlen-in-alloc 4============================================== 5 6Finds cases where ``1`` is added to the string in the argument to ``strlen()``, 7``strnlen()``, ``strnlen_s()``, ``wcslen()``, ``wcsnlen()``, and ``wcsnlen_s()`` 8instead of the result and the value is used as an argument to a memory 9allocation function (``malloc()``, ``calloc()``, ``realloc()``, ``alloca()``) or 10the ``new[]`` operator in `C++`. The check detects error cases even if one of 11these functions (except the ``new[]`` operator) is called by a constant function 12pointer. Cases where ``1`` is added both to the parameter and the result of the 13``strlen()``-like function are ignored, as are cases where the whole addition is 14surrounded by extra parentheses. 15 16`C` example code: 17 18.. code-block:: c 19 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 not 26to its argument. In the example above the fix would be 27 28.. code-block:: c 29 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 to 43add ``1`` to the return value of ``strlen()`` and not to its argument. In the 44example above the fix would be 45 46.. code-block:: c++ 47 48 char *c = new char[strlen(str) + 1]; 49 50 51Example for silencing the diagnostic: 52 53.. code-block:: c 54 55 void bad_malloc(char *str) { 56 char *c = (char*) malloc(strlen((str + 1))); 57 } 58