Every developers need to be trained in secure coding practices. I don’t actively code in my day-to-day work anymore, but I don’t want to loose the skill. As a recommendation, Stanford’s secure coding course is interesting. I learnt C during the under graduation. We progressed from Fortran to Cobol and finally C, the magical language that let you manipulate the system memory. I had not used C after I joined work force, but I always had an admiration to that family of programming languages. That was the prime reason I chose to focus on C# when it’s initially launched in 2002.
Anyway, back to the topic. Learning secure coding techniques is interesting and I had never heard this problem of underflow and overflow. Well, maybe I forgot!
Here is the issue:
What is the issue with this code?

The provided C code initializes an unsigned integer variable a to the value 4, subtracts 3 from it (a = a - 3), and then prints the result of subtracting 2 from a. Let’s evaluate the code step by step:
- Initialize
ato 4. - Subtract 3 from
a:a = 4 - 3, resulting ina = 1. - Print the result of subtracting 2 from
a:printf("%u\n", 1 - 2).
Now, evaluating the expression inside printf:

The result is -1. However, since a is declared as an unsigned integer (%u in the printf format specifier), the value will be interpreted as an unsigned integer. In C, under the rules of unsigned integer arithmetic, subtracting a larger value from a smaller value result in wrapping around the maximum value representable by the data type.
The maximum representable value for an unsigned 32-bit integer is 4294967295.
Therefore, the output of the code will be:

This is the result of interpreting the arithmetic underflow as an unsigned value within the specified data type.
Modern languages such as Java and .NET will avoid this issue and provide type safety. Rust is another interesting language that could replace C, C++ mitigating the issues around type safety and all.
Leave a comment