CAUTION!

CAUTION! DANGER ZONE ahead. Beware of misinformation on the open internet. Contents of the site are mere opinions and are not always facts!

Wednesday, August 27, 2014

Unsigned int overflow in decrementing loops

A case study of interger overflow's impact on iterators. when an unsigned integer is used in decrementing "for" loops. The loop unexpectedly iterates indefinitely if the loop had to terminate when the value becomes lesser than 0.

for(unsigned int i = length; i >= 0; --i)
{
    //...
}

Since an unsigned integer is used, decrementing the variable to lesser than 0 will roll the value back to the
MAXIMUM_VALUE
that can be stored in the variable (depending on its size, usually 4 bytes - on 32 or 64 bit Windows), which is always >=0.

One possible solution is to terminate the loop when the value becomes greater than the initial assigned value or equal to the
MAXIMUM_VALUE
.

for(unsigned int i = length; i <= length; --i)
{
    //...
}

for(unsigned int i = length; i != MAXIMUM_VALUE; --i)
{
    //...
}

Another solution would be to reserve 0 for the terminating condition. Note that the length should not be equal to
MAXIMUM_VALUE
. Thus, a variable can be used to iterate a maximum count of
MAXIMUM_VALUE
.
for(unsigned int i = length + 1; i > 0; --i)
{
    //Use i-1 ...
}
But, why use unsigned int at all? a signed integer does not have this problem. Because, unsigned integer have wider positive values range than the signed integer.

positive value range for signed integer: 0 to std::numeric_limits<signed  int >::max()
positive value range for unsigned integer: 0 to std::numeric_limits<unsigned  int >::max()

where, std::numeric_limits<signed  int >::max() std::numeric_limits<unsigned  int >::max()

Wednesday, August 6, 2014

Is C++ truly cross-platform?

Is C++ truly cross-platform?

The answer is yes! the C++ language standard is. Code written to comply with this standard is cross platform.

Porting the code to various platforms gets difficult when non standard code is written to accomplish more useful tasks.

1. We need OS APIs for Multi-Threading, Networking, GUI etc. There are several cross platform (common interface with different implementations) libraries like Boost, QT, libcurl, cpp-netlib etc that provide the same OS specific functionality on different platforms.

2. The code should be compiled for different platforms and we need compilers that supports the same version of C++ on different platforms. Compiler specific types or directives shouldn't be used.

3. Non standard use cases like character encoding and Endianness should be considered.

Non standard code can anymore be avoided with the introduction of new versions of C++, C++11 and C++14; and cross platform compilers, Clang.

Thus, writing truly cross platform C++ should be a piece of  ðŸŽ‚!!!