Library tutorials & articles

Typical errors of porting C++ code on the 64-bit platform

Use of the functions with a variable number of arguments

The typical example is the incorrect use of printf, scanf functions and their variants:

1) const char *invalidFormat = "%u";
   size_t value = SIZE_MAX;
   printf(invalidFormat, value);

 

2) char buf[9];
   sprintf(buf, "%p", pointer);

In the first case it is not taken into account that size_t type is not equivalent to unsigned type on the 64-bit platform. It will cause the printing of an incorrect result in case if value > UINT_MAX.

In the second case the author of the code didn’t take into account that the pointer size may become more than 32-bit in future. As a result this code will cause the buffer overflow on the 64-bit architecture.

The incorrect use of functions with a variable number of arguments is a typical error on all the architectures, not only on 64-bit ones. This is related to the fundamental danger of the use of the given C++ language constructions. The common practice is to refuse them and use safe programming methods. We recommend you strongly to modify the code and use safe methods. For example, you may replace printf with cout, and sprintf with boost::format or std::stringstream.

If you have to support the code which uses functions of sscanf type, in the control lines format we can use special macros which open into necessary modifiers for different systems. An example:

// PR_SIZET on Win64 = "I"
// PR_SIZET on Win32 = ""
// PR_SIZET on Linux64 = "l"
// ...
size_t u;
scanf("%" PR_SIZET "u", &u);

Comments

  1. 01 Jan 1999 at 00:00

Leave a comment

Sign in or Join us (it's free).

Andrey Karpov
AddThis

Related podcasts

  • Interview with Shawn Burke on Microsoft's .NET Source Code Release

    Scott and Carl talk with Shawn Burke on the culmination of his many-year-old plan to get parts of the source of the .NET Framework released. With Visual Studio 2008, a simple process will allow developers to STEP INTO the .NET Framework Source from the IDE. This'll be a great debugging and learni...

We'd love to hear what you think! Submit ideas or give us feedback