1

The problem is very simple: given start_index and count, I want to see if the combinations can be used to safely accessed an array with length elements. What I have for the time being is the following:

uint32_t start_index = (value from somewhere);
uint32_t count = (value from somewhere);
uint32_t length = (value set earlier);
char *array = (memory allocated earlier);

if(start_index + count < length) {
    // access array starting at start_index
} else {
    // bailout
}

The check is, of course, inadequate since start_index + count can exceed the maximum possible value for an uint32_t and wrap around to a small value. To fix this, I wonder if it's more efficient to promote the variables to 64 bit or put in a second condition start_index + count > start_index. Or perhaps there's some other clever way to handle this?

1
  • There is a long list of methods to detect integer overflows before or after the fact here. Commented Feb 8, 2013 at 5:41

1 Answer 1

2

You can avoid overflows by doing things a bit differently: first check that count is smaller than length (bail out otherwise), then you can safely compare start_index with length - count.

Sign up to request clarification or add additional context in comments.

2 Comments

2 people don't see an off by one error here. Come on, count smaller than OR EQUAL length.
If length == count, the original code (assuming no overflow issues) would bail out. My suggestion would bail out too. So I don't believe there is an OBOE here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.