Tuesday, August 31, 2010

How to bound check arrays in cpp / c

Bound checking in cpp /c is headache....
char *strcpy(char *dest, const char *src)
char *save = dest;
while(*dest++ = *src++);
return save;

//main func
char *src = "hello to c programming language";
char dest[12];

strcpy(dest,src); //calling function

Here we have no bound check on dest size or src size. When we pass it to function it is perfectly alright but
problem is dest is array which is just 12 bytes long...but src is larger string...

So if programmer is lucky , he gets Error - "Segmentation fault"
else in worse case, he gets his core dumped...that is his memory may have changed the effect of it can be seen after few days.

What's the solution?
We cant change this library function to check bound check, like sending size to it with both src and dest...because many programs might be using it...and this change may hamper these million of programs. So it is the responsibility of programmer to check whether he has provided enough space or not?
Note: There is no way right now to check bounds by [] operator.

A vector will do bounds checking if you use the at() function, for example:
std::vector v(5);
.at(3) = 10;
.at(5) = 20; // throws an exception, std::out_of_range
However, if you use operator[], there is no bounds checking. (And accessing non-existent elements leads to undefined behavior.)

No comments:

Post a Comment