carl.hiass
carl.hiass

Reputation: 1774

Array bounds checking

It seems with arrays it's easy to get an off-by-one error:

short xar[2] = {};
for (int i = 0; i <= sizeof(xar)/sizeof(*xar); ++i) {
    xar[i-1]=i*i;
    printf("Element i = %d\n", xar[i]);
}

Element i = 0
Element i = 0
Element i = -9272

Is there a good way to check for the out-of-bounds case? Or how is something like this usually done (it seems writing out of bound array values would be super easy to do!)

Upvotes: 1

Views: 1326

Answers (1)

Alex
Alex

Reputation: 632

C as a language does not provide any provisions for bounds-checking beyond "keep track of it yourself". So there is not really a better solution in general other than being careful. There do exist programs like ASAN which can help detect such bugs at runtime though.

Upvotes: 1

Related Questions