C language > Expert questions

How can I test a numeric string overflow?

<< < (2/4) > >>

frankie:
Remove the test of last bit set, and try the function for "42949672959"...
Then put back the test before use it in your code! ;)
The check prevents a wraparound that could result on an overflowed value still satisfying the check 'tmp > v'.
Checking last bit reports future overflow before multiplication (just doubling it gives an overflow).

John Z:
if you are only interested in a limited case of unsigned int 32, then send the incoming string to a Larger storage variable then compare to int32_max.  Check string length less than 11 chars (because if more then alreay too large), then atoll(p) to a long long variable then check if > 4294967295 or int_max.  Can generalize ot other sizes if passing size specifier along with string pointer.
Ends up simply
check length
convert to larger storge
compare to max

frankie:
I understood that he don't want use any library function and operate natively.
Maybe also the use of larger storage should be avoided?

John Z:
Ah, sorry I see that now.... "(natively, without using any library!)"

PaoloC13:

--- Quote from: frankie on May 04, 2020, 03:08:57 PM ---Remove the test of last bit set, and try the function for "42949672959"...
Then put back the test before use it in your code! ;)
--- End quote ---
Yes, it was the case I was looking for and that I had missed. Thanks.
But then, I found other cases that provides an exception, for example:

UIntOverflow("8589934590"); // No owerflow!

Navigation

[0] Message Index

[#] Next page

[*] Previous page

Go to full version