| 1 |
.. title:: clang-tidy - bugprone-multi-level-implicit-pointer-conversion |
| 2 |
|
| 3 |
bugprone-multi-level-implicit-pointer-conversion |
| 4 |
================================================ |
| 5 |
|
| 6 |
Detects implicit conversions between pointers of different levels of |
| 7 |
indirection. |
| 8 |
|
| 9 |
Conversions between pointer types of different levels of indirection can be |
| 10 |
dangerous and may lead to undefined behavior, particularly if the converted |
| 11 |
pointer is later cast to a type with a different level of indirection. |
| 12 |
For example, converting a pointer to a pointer to an ``int`` (``int**``) to |
| 13 |
a ``void*`` can result in the loss of information about the original level of |
| 14 |
indirection, which can cause problems when attempting to use the converted |
| 15 |
pointer. If the converted pointer is later cast to a type with a different |
| 16 |
level of indirection and dereferenced, it may lead to access violations, |
| 17 |
memory corruption, or other undefined behavior. |
| 18 |
|
| 19 |
Consider the following example: |
| 20 |
|
| 21 |
.. code-block:: c++ |
| 22 |
|
| 23 |
void foo(void* ptr); |
| 24 |
|
| 25 |
int main() { |
| 26 |
int x = 42; |
| 27 |
int* ptr = &x; |
| 28 |
int** ptr_ptr = &ptr; |
| 29 |
foo(ptr_ptr); // warning will trigger here |
| 30 |
return 0; |
| 31 |
} |
| 32 |
|
| 33 |
In this example, ``foo()`` is called with ``ptr_ptr`` as its argument. However, |
| 34 |
``ptr_ptr`` is a ``int**`` pointer, while ``foo()`` expects a ``void*`` pointer. |
| 35 |
This results in an implicit pointer level conversion, which could cause issues |
| 36 |
if ``foo()`` dereferences the pointer assuming it's a ``int*`` pointer. |
| 37 |
|
| 38 |
Using an explicit cast is a recommended solution to prevent issues caused by |
| 39 |
implicit pointer level conversion, as it allows the developer to explicitly |
| 40 |
state their intention and show their reasoning for the type conversion. |
| 41 |
Additionally, it is recommended that developers thoroughly check and verify the |
| 42 |
safety of the conversion before using an explicit cast. This extra level of |
| 43 |
caution can help catch potential issues early on in the development process, |
| 44 |
improving the overall reliability and maintainability of the code. |