- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to detect integer overflow in C++?
45 Lectures 4.5 hours
66 Lectures 5.5 hours
The only safe way is to check for overflow before it occurs. There are some hacky ways of checking for integer overflow though. So if you're aiming for detecting overflow in unsigned int addition, you can check if the result is actually lesser than either value-added. So for example,
unsigned int x, y; unsigned int value = x + y; bool overflow = value < x; // Alternatively "value < y" should also work
This is because if x and y are both unsigned ints if added and they overflow, their values can't be greater than either of them as it would need to be greater than max possible unsigned int to be able to wrap around and get ahead of these values.
Another way is to try and access the Overflow flag in your CPU. Some compilers provide access to it which you could then test but this isn't standard.
There are other ways to achieve this but they provide estimates only. You can check them out here − https://stackoverflow.com/a/199455/3719089
- How to detect integer overflow in C/C++?
- Check for Integer Overflow in C++
- Java Program to check for Integer overflow
- Check for integer overflow on multiplication in C++
- Heap overflow and Stack overflow
- Heap overflow and Stack overflow in C
- How to Detect Keyloggers?
- How to detect eventType in jQuery?
- How to change android overflow menu icon programmatically?
- Buffer Overflow Attack: Definition, Types, How to Avoid
- CSS overflow: visible
- CSS overflow: hidden
- CSS overflow: scroll
- CSS overflow: auto
- CSS overflow-y