Writing Your Last For-Loop - Beautiful Code
beautifulcode.oreillynet.com
beautifulcode.oreillynet.com
for(int n = 0; n < size; ++n)
sum += elements [n];
Leaving aside the stylistic question of declaring variables in the middle of a for statement, and trusting that the author knows that the variable sum will never overflow and (if he's dealing with floating-point values) that rounding errors won't matter, the code should still be for(size_t n = 0; n < size; ++n)
sum += elements [n];
An index to an array should always be declared as size_t, not as int. Otherwise really bad things can happen on systems where size_t is 64 bits but int is 32 bits.EDIT: Before someone accuses me of being overly pedantic: I've lost count of how many security issues I've fixed which have existed because someone used int where they meant size_t, but it's at least in the double-digits.
But you are right - C can be used as a higher level version of assembly.
On LP64, integers are 32 bits and size_t must be 64 bits (or you could overflow it with otherwise legal code).
Even when integer and size_t are the same size, using an integer as an array index is dangerous unless you make sure that it is not negative and can never become negative.
Here's what easily exploitable code looks like:
void pad_ten(char *array, size_t length) {
if(length < 10) {
error();
return;
}
for(int i = (length - 10); i < length; i++) {
array[i] = doPadding();
}
}It's exploitable by either choosing a 'length' which becomes negative when assigned to the integer or choosing a 64 bit 'length' which becomes an entirely different (and incorrect) value when truncated to an integer.
90% of your code should either be generated or copied from standard templates. I've put over 2500 new programs into the library in the past couple of years, yet I don't remember the last time I wrote a program from scratch.
I, too, am a stickler for details, but I let the compiler (or interpreter) do its job. Why worry about nanoseconds when I have users running the asylum?
And it's usually not about performance for me. I like code that looks good and is dense.