cleong
cleong

Reputation: 7606

Bound checking and integer overflow

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?

Upvotes: 1

Views: 413

Answers (1)

Mat
Mat

Reputation: 206689

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.

Upvotes: 2

Related Questions