How To Properly Check That An Off_t Value Won't Overflow When Converted To Size_t In C?
I need to cast an off_t variable to a size_t variable, and I want to detect if an overflow might happen. In C.
My initial attempts looks like this:
off_t fsize;
size_t len;
...
if(fsize >= 0 && fsize <= SIZE_MAX) {
len = (size_t)fsize;
} else {
abort();
}
However, the compiler doesn't like my comparison between a signed and unsigned types (fsize <= SIZE_MAX). I can't really make assumptions about the respective sizes of the off_t and size_t types either.
Answer
I can't really make assumptions about the respective sizes of the off_t and size_t types either.
To compare mixed signed types whose comparable ranges are no clearly tied, cast to uintmax_t
.
Once code knows the signedfsize >= 0
is true, casting to a wide unsigned type like uintmax_t
will certainly not narrow the fsize
value and quiet the warning.
if (fsize >= 0 && (uintmax_t) fsize <= SIZE_MAX) {
If the cast to uintmax_t
is unnecessarily wide, I'd expect the compiler to still emit efficient code.
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page