I'm pretty sure catching this in all cases would involve solving the Halting Problem.
fn maybe_alloc() -> Vec<usize> {
if collatz_conjecture_is_true() {
vec![42]
} else {
vec![]
}
}
fn main() {
let v = maybe_alloc(); // Does this allocate?
}But I feel like a static analyzer could clearly identify “this line can allocate” just by knowing what language features can allocate. And for third party library methods “does this function have anything inside of it that could allocate?”
You can't know for sure if all of those places are reachable in a running program, but that's not necessary to solve this problem.