537 HIKES and counting

Top Stories

Lava Kafle


C++ Programming: Static Code Analysis and the New Language Standard C++0x – CodeGuru

This function cannot work on a 64-bit system with large arrays. If the 
variable arraySize has a value more than UINT_MAX, the condition 
"i < arraySize" will never be fulfilled and an eternal loop will 

occur.bool IsPresent(char *array,
               size_t arraySize,
               char key)
  for (unsigned i = 0; i < arraySize; i++) 
    if (array[i] == key)
      return true;
  return false;

warning C4267: 'initializing' : 
conversion from 'size_t' to 'unsigned int', possible loss of data
void f(const vector<int>& a,
       vector<float>& b)
  typedef decltype(a[0]*b[0]) Tmp;
  for (int i=0; i<b.size(); ++i)
    Tmp* p = new Tmp(a[i]*b[i]);
    // ...

This code has a 64-bit error: the function behaves correctly when compiling the Win32 version and fails when the code is built in the Win64 mode. The error is in using the type unsigned for the variable “n”, although the type string::size_type must be used which is returned by the function find(). In the 32-bit program, the types string::size_type and unsigned coincide and we get correct results. In the 64-bit program, string::size_type and unsigned do not coincide any more. When the substring is not found, the function find() returns the value string::npos that equals 0xFFFFFFFFFFFFFFFFui64. This value is cut to the value 0xFFFFFFFFu and placed into a 32-bit variable. As a result, the condition 0xFFFFFFFFu != 0xFFFFFFFFFFFFFFFFui64 is true and we have the situation when the function Find_Incorrect always returns true.

C++ Programming: Static Code Analysis and the New Language Standard C++0x – CodeGuru.