3 ms·
In theory, a new first-class slice type could only provide a “checked” interface, meaning that accesses through it would only succeed if in bounds. In practice
by woodruffw 3y ago
In theory, a new first-class slice type could only provide a “checked” interface, meaning that accesses through it would only succeed if in bounds.
In practice, C doesn’t have great idioms for error handling, and so a proposal here would also probably need to explain how the slice type would either reuse existing idioms or introduce a new idiom (like Rust’s use of sum types). That makes the scope much larger, which in turn might explain any hesitancy from the C WGs to accept something like this (although I’m not actually aware of any).
- mjevans 3y agoProbably a warning flag that notes any non-compile time bounds checked references. Now that you mention it, some method of forcing bounds checks in more limited circumstances might be nice for performance, that or a cleaner method of expressly disabling such for areas with critical performance and where the input is considered trusted or already validated.
- WalterBright 3y agoThe array can be simply converted to a pointer to get unchecked access.
- WalterBright 3y agoArray bounds errors in D are treated as "go directly to jail, do not pass Go do not collect $200" errors. I.e. they are not recoverable, so no need for error handling. Many people have debated this and wanted such errors to be recoverable, but the principle in play is that the program is in an undefined state if there are such errors, and should not be allowed to continue as we wouldn't want it to launch nuclear missiles.
- woodruffw 3y agoThat’s (IMO) the right way to do it, but it’s also a harder pill to swallow from the C standards side: functions that die as a side effect rather than being UB are less precedented, have to be taught differently, etc. C’s lack of iterators also means that indexing bugs are more likely in idiomatic C programs than they are in equivalent C++ or D programs. This is another place where the standards body should improve things, but it also means that they’re somewhat constrained when it comes to slice proposals: making every index be potentially fatal is less palatable when your programming language doesn’t divert people away from indexing as much as it could.
- CodesInChaos 3y agoSince dying is a valid implementation of UB, I don't see a problem. It's definitely better than memory corruption. In general my preferred way to handle OOB is an unchecked exception (like in Rust or C#), but that's not really an option C.