Check for arithmetic overflow/underflow

Posted: 2012-03-08 in .Net

Below is a code snippet from a program that deals with rather large and many files and puts them into VFS’s.

I had a client get the BadLuckException, even though everything seemed to be set correctly
I have hard coded the values to make things easier to spot/read.

long totalFileSize = 7094336; //Bytes
int memsize = 4096; //MB

if (totalFileSize > (memSize – 1) * 1024 * 1024) //convert Mb to Bytes
throw new BadLuckException(“Not enough memory allocated to hold the files”);

When the exception was raise I was a little surprised debugging gave me that i had an over flow on the bottom row (value of -1017084 or something similar).
I not sure why but i always assume inline statements to take the temp value of the largest value in the equation. To me it just made logic sense? or does it? šŸ˜€

One of my ever so brainy co-worker hinted that it is much easier to trace these problems if you enable “Check for arithmetic overflow/underflow” when compiled in Debug mode. For once I had to agree :D.
This option is set for each project by navigating to “Project Properties” -> “Build” -> “Advanced..”. The check box is in the Advanced Build settings box that pops up.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s