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?

cleong
  • 7,242
  • 4
  • 31
  • 40
  • There is a long list of methods to detect integer overflows before or after the fact [here](http://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-c-c). – Richard Feb 08 '13 at 05:41

1 Answers1

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 2 people don't see an off by one error here. Come on, `count` smaller than OR EQUAL `length`. – Alexey Frunze Feb 08 '13 at 06:11
  • 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. – Mat Feb 08 '13 at 06:35