-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New lint: Performing arithmetic on numeric value of function pointer #9517
Comments
There’s an experiment about forbidding them: rust-lang/rust#95228 first comments talk about a lint, which I haven’t found traces about |
That's a very long-term change, and actually disallowing |
|
I don't think this related to |
The "side effect" here would be a wrong or surprising arithmetic result that can produce wrong final outputs but regardless of the merit, I honestly don't want to ride the ol' debate train. As such, I withdraw my participation in this use case. |
Seem it’s already implemented with clippy::fn_to_numeric_cast_any |
Yes, this is about forbidding all ptr to int So that is indeed mostly unrelated to the |
Did you wanted to say related? I tried on the playground and |
Sorry, with "that" I meant the |
This is not the same thing as clippy::fn_to_numeric_cast_any. There are legitimate usecases for casting a function pointer to a numeric type (even if those eventually turn into explicit provenance-api calls in new editions). However, multiplying or dividing by that value (or any pointer-derived numeric value) is pretty much guaranteed to be a bug. |
What it does
This lints on any expression of the form
some_arithmetic_expr(function_pointer as NumericType, other_type)
.For example (note the lack of parenthesis - all of the function used here are function pointers)
Lint Name
function_pointer_arithmetic
Category
correctness
Advantage
Performing arithmetic on a function pointer value (cast as a numeric type) is virtually never correct. Rust provides no guarantees about the relative location of functions in memory, or the actual in-memory assembly code at a function's address. In particular, multiplying or dividing by a pointer value is completely meaningless.
Drawbacks
None
Example
When writing low-level code, it's often useful to calculate sizes by multiplying by
std::mem::size_of::<SomeType>
. For example:However, Rust allows casting a function pointer to any numeric type. If you accidentally commit the parenthesis in the function call, you'll obtain the following valid code:
This multiplies a function address by
num_elements
, which is completely useless. The overall result will be completely unrelated to the size ofMyType
(and depending on the address ofstd::mem::size_of::<MyType>
, it may also be very large). The code looks almost identical to the correct version, which could make it very difficult to notice the cause of the incorrect value.The text was updated successfully, but these errors were encountered: