How to check for variable overflow?
Go to solution
Solved by BobVonBob,
Most string to numeric converting functions have bounds checking, and the ones that don't shouldn't be used on values that could be outside of the acceptable range. In the case of C with an unsigned integer you would generally use strtoul(), which sets errno if the value is out of bounds. You can check that as follows:
#include <errno.h> #include <stdlib.h> int main(void) { const char *strNum = "-40"; char *end = NULL; unsigned int num = strtoul(strNum, &end, 10); // overflows if (errno == ERANGE) { // You've just had a range error errno = 0; } }
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now