| View previous topic :: View next topic |
| Author |
Message |
Sven Schüle
Joined: 15 May 2008 Posts: 2242 Location: Berlin, Germany
|
Post subject: Re: Finding errors where indexes goes beyond their boudaries Posted: Sun May 06, 2012 9:46 pm |
|
|
| Code: |
char testIdx;
char test50a[50];
char test50b[50];
testIdx=75; // outside the array
// ok to read from outside the array?
test50a[25]=test50a[testIdx];
// ok to write outside the array?
test50a[testIdx]=test50a[25]; |
1. For "testIdx", I'd better use "unsigned int" instead of "char".
2. The compiler can only find such array bounds errors if a variable like "testIdx" is declared as "const", or (maybe) if it is "static" and the compiler is able to see that there is no other code in the same compilation unit that changes its value. In almost all other cases the compiler has no chance to detect this kind of array bounds violation since it has no knowledge about the value of the array index when compiling the array access code.
3. I don't know which compiler you are using with "DevCpp". GCC for instance has -Warray-bounds which "warns about subscripts to arrays that are always out of bounds" (but in real programs this is hard to find). The runtime option "-fbounds-check" seems to be for Java and Fortran only. Compilers like MSVC(++) or Intel C(++) have an option to check for array bounds violation at runtime. Typically you switch it off for an optimized version. Still no chance, though, for a compile time detection, at least in a more complex "real world" case.
4. The "right" solution, as already mentioned, is to use something like the standard assert() macro, as in this silly example:
| Code: |
#include <assert.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
char test50a[50];
char test50b[50];
inline char getTest50A(unsigned int idx)
{
assert(idx < ARRAY_SIZE(test50a));
return test50a[idx];
}
inline char getTest50B(unsigned int idx)
{
assert(idx < ARRAY_SIZE(test50b));
return test50b[idx];
} |
Only the debug version will actually do the bounds check so you can use it for thorough testing, while the release version, compiled with the "NDEBUG" preprocessor switch, will omit it. This concept is more general than any specific array bounds checking option and may have some other usability advantages, so I'd always prefer it.
5. There are various tools for static code analysis, some of them also open source.
6. Why are you using DevCpp?
Sven |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|