by steveklabnik · 3y ago · 0 comments
If you do run into memory unsafety in rust, you already have signposts pointing towards possible problems. You get very little help in comparison in C++.
int oops[10];
oops[69] = 420; int x = 0x7fffffff;
x++;
Or: std::array<uint32_t, 2> x = {1, 2};
uint64_t *y = (uint64_t *)&x;
*y;
Or: std::optional<int> x;
*x;
Or: std::variant<std::string_view, int> x;
x = "foo";
auto &y = std::get<std::string_view>(x);
x = 42;
std::cout << y; idiot.c:4:3: warning: array index 69 is past the end of the array (which
contains 10 elements) [-Warray-bounds]
oops[69] = 420;
^ ~~
idiot.c:3:3: note: array 'oops' declared here
int oops[10];
^
But... if 69 is replaced with a user-supplied argument, then that bypasses the detection. int idx = atoi(argv[1]);
int oops[10];
oops[idx] = 420;And so the runtime Panic will occur in Rust only for the dynamic case.
Notice that in WUFFS the user argument code is still a compile time error. WUFFS wants to know why you thought it would be OK to put arbitrary numbers in idx, a variable you are using to index into an array of size 10, and thus which should only have values between 0 and 9 inclusive. It won't be happy until you write logic to ensure this can't happen.