| 1 |
.. title:: clang-tidy - bugprone-misplaced-pointer-arithmetic-in-alloc |
| 2 |
|
| 3 |
bugprone-misplaced-pointer-arithmetic-in-alloc |
| 4 |
=============================================== |
| 5 |
|
| 6 |
Finds cases where an integer expression is added to or subtracted from the |
| 7 |
result of a memory allocation function (``malloc()``, ``calloc()``, |
| 8 |
``realloc()``, ``alloca()``) instead of its argument. The check detects error |
| 9 |
cases even if one of these functions is called by a constant function pointer. |
| 10 |
|
| 11 |
Example code: |
| 12 |
|
| 13 |
.. code-block:: c |
| 14 |
|
| 15 |
void bad_malloc(int n) { |
| 16 |
char *p = (char*) malloc(n) + 10; |
| 17 |
} |
| 18 |
|
| 19 |
|
| 20 |
The suggested fix is to add the integer expression to the argument of |
| 21 |
``malloc`` and not to its result. In the example above the fix would be |
| 22 |
|
| 23 |
.. code-block:: c |
| 24 |
|
| 25 |
char *p = (char*) malloc(n + 10); |