Open hvdijk opened 1 year ago
Also, Vec
is heap-allocated and alloca
is stack-allocated. Shouldn't we try to preserve this?
Also,
Vec
is heap-allocated andalloca
is stack-allocated. Shouldn't we try to preserve this?
Ideally, yes, but that may not be possible as Rust does not have alloca
. There was an RFC to add it, https://github.com/rust-lang/rfcs/issues/618, but it was closed in favour of https://doc.rust-lang.org/beta/unstable-book/language-features/unsized-locals.html. The unsized-locals feature, I believe, will be a suitable replacement for many uses of alloca
, but not all of them, and not the one in the example I gave here. However, as the unsized-locals feature is not yet finalised, it is possible that it will be extended and become a full replacement.
That only handles a subset of the possible uses of alloca
as well, and I suspect it may be a smaller subset than what will be handled by that unsized-locals feature once that includes VLAs.
Tested with c2rust 0.16.0
This is a program that has no memory errors. The
if (one)
is guaranteed to be entered, though the compiler cannot see that, and the result of__builtin_alloca
persists until the function ends, even after the block has ended.It is translated to the following Rust code:
Note here the
let mut fresh0 = ::std::vec::from_elem(0, 100 as libc::c_int as libc::c_uint as usize);
in block scope. Here, unlike in the C program, the vec will be dropped when the block is exited, andp
is left a dangling pointer.A possible corrected translation would be to make
fresh0
a function-scope variable.