1 .. title:: clang-tidy - bugprone-misplaced-operator-in-strlen-in-alloc
3 bugprone-misplaced-operator-in-strlen-in-alloc
4 ==============================================
6 Finds cases where ``1`` is added to the string in the argument to ``strlen()``,
7 ``strnlen()``, ``strnlen_s()``, ``wcslen()``, ``wcsnlen()``, and ``wcsnlen_s()``
8 instead of the result and the value is used as an argument to a memory
9 allocation function (``malloc()``, ``calloc()``, ``realloc()``, ``alloca()``) or
10 the ``new[]`` operator in `C++`. The check detects error cases even if one of
11 these functions (except the ``new[]`` operator) is called by a constant function
12 pointer. 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
14 surrounded by extra parentheses.
20 void bad_malloc(char *str) {
21 char *c = (char*) malloc(strlen(str + 1));
25 The suggested fix is to add ``1`` to the return value of ``strlen()`` and not
26 to its argument. In the example above the fix would be
30 char *c = (char*) malloc(strlen(str) + 1);
37 void bad_new(char *str) {
38 char *c = new char[strlen(str + 1)];
42 As in the `C` code with the ``malloc()`` function, the suggested fix is to
43 add ``1`` to the return value of ``strlen()`` and not to its argument. In the
44 example above the fix would be
48 char *c = new char[strlen(str) + 1];
51 Example for silencing the diagnostic:
55 void bad_malloc(char *str) {
56 char *c = (char*) malloc(strlen((str + 1)));