Aug 052014
 

The C Runtime is being refactored…

Note CRT is being refactored. The implementation is split into different modules. Read more here: http://blogs.msdn.com/b/vcblog/archive/2014/06/10/the-great-crt-refactoring.aspx

Relevant excerpt from above blog post:

In order to unify these different CRTs, we have split the CRT into three pieces:

  1. VCRuntime (vcruntime140.dll): This DLL contains all of the runtime functionality required for things like process startup and exception handling, and functionality that is coupled to the compiler for one reason or another. We mayneed to make breaking changes to this library in the future.
  2. AppCRT (appcrt140.dll): This DLL contains all of the functionality that is usable on all platforms. This includes the heap, the math library, the stdio and locale libraries, most of the string manipulation functions, the time library, and a handful of other functions. We will maintain backwards compatibility for this part of the CRT.
  3. DesktopCRT (desktopcrt140.dll): This DLL contains all of the functionality that is usable only by desktop apps. Notably, this includes the functions for working with multibyte strings, the exec and spawn process management functions, and the direct-to-console I/O functions. We will maintain backwards compatibility for this part of the CRT.
Oct 022013
 

You might notice that when comparing with NaN, the comparison gives wrong results at least for x64 builds. Take a look at the following piece of code. If you run this sample application the comparison statement if(lfv==0.0) returns true and the MessageBox is displayed. (We had a customer who reported this behavior.)

#include "stdafx.h"
#include <limits>


int _tmain(int argc, _TCHAR* argv[])
{
    double lfv = std::numeric_limits<double>::quiet_NaN();

    if (lfv == 0.0)
        ::MessageBox(::GetActiveWindow(), _T("Equal"), argv[0], MB_OK);

    return 0;
}

If you put a breakpoint at the if statement, this is what the debugger shows as values for lfv. lfv is definitely not zero.

image

So why is the comparison behaving weird. The reason for this issue is that you’ve disable precise comparison of floating point values via the compiler switch /fp:fast. To fix this you should change to /fp:precise. This can be done via project properties dialog as well…

image

So you might ask why does it behave well for x86 builds? The answer is that comparing NaN’s with /fp:fast result in undefined behavior. So it is OK for the comparisons to behave differently on different targets with this option.

You should be aware of all the implications of using /fp:fast in VC++ and one of them is undefined behavior for NaN comparisons. This is the way VC++ specifies how /fp:fast behaves and is likely due to implementation constraints. Other compilers may produce the correct result for such compares but that is because each compiler has its own specification of what /fp:fast means.

Now you might think just for one comparison should I enable /fp;precise? The answer is that you can enable this feature per compilation unit or per function. Check out following link for details: http://msdn.microsoft.com/en-us/library/45ec64h6.aspx

The above link talks about the float_control pragma. So in order to fix above code we can do this instead of turning on /fp:precise for the entire project…

#include "stdafx.h"
#include <limits>

#pragma float_control(precise, on)

int _tmain(int argc, _TCHAR* argv[])
{
    double lfv = std::numeric_limits<double>::quiet_NaN();

    if (lfv == 0.0)
        ::MessageBox(::GetActiveWindow(), _T("Equal"), argv[0], MB_OK);

    return 0;
}
#pragma float_control(precise, off)

Or if you have too many functions you can enable /fp:precise per cpp file or per compilation unit. Right click on the cpp file, select properties and navigate to the following property and change it to /fp:precise

image

This should will help solve your comparison failures with NaN values.

Oct 012013
 

Interview Question…

I have following code snippets…

Code snippet 1
int arr[1000000];
int main()
{   
	return arr[0];
}
Code snippet 2:
int arr[1000000] = {10};
int main()
{   
	return arr[0];
}

After compilation of the above snippets the output exe differs in size. The second snippet’s executable is much bigger in size than the first snippet’s executable. See screenshot…

image

Why?

 

Sep 132013
 

This one is a brain teaser for my native programmers.

Prove via code the direction of a threads’ stack growth i.e is it upwards or downwards.

Post your answer as a comment. I’ll post mine in a while.

Feb 212011
 

Hmm so after a long time I’m back with a new post.

This time I came across a cool API called NtQueryObject. One purpose of the API is to find the name of object type it’s given. For example if you are passing a process handle this API will return “Process” as the string. The caveat of using this API is that it can be changed in the future. So be very careful with the signature of the function, cross check with the documentation before using. Use it at your own risk.

So let’s see the code, since API doesn’t have a lib associated with it we’ll have to use GetProcAddress to retrieve function address. The function signature of NtQueryObject looks like…

NTSTATUS NtQueryObject(__in_opt HANDLE Handle,
                        __in OBJECT_INFORMATION_CLASS ObjectInformationClass,
                        __out_opt PVOID ObjectInformation,
                        __in ULONG ObjectInformationLength,
                        __out_opt PULONG ReturnLength );

The second parameter to the API can be of two types. The one type of interest for this case is PUBLIC_OBJECT_TYPE_INFORMATION. If we pass this type as second parameter then the API is expecting a PUBLIC_OBJECT_TYPE_INFORMATION as third parameter. The contents of the structure is as follows…

typedef struct __PUBLIC_OBJECT_TYPE_INFORMATION {
    UNICODE_STRING TypeName;
    ULONG Reserved [22];    // reserved for internal use
} PUBLIC_OBJECT_TYPE_INFORMATION, *PPUBLIC_OBJECT_TYPE_INFORMATION;

The first member in the structure is the one that returns the string, only issue we’ll have to allocate this in special manner. Please have a look in the below function to see how I’ve allocated memory for this structure.

void GetHandleTypeName(HANDLE hHandle, CString&amp;amp;amp; TypeName)
{
 typedef NTSTATUS (NTAPI *NtQueryObjectPtr)(HANDLE Handle,
                   OBJECT_INFORMATION_CLASS ObjectInformationClass,
          PVOID ObjectInformation,
          ULONG ObjectInformationLength,
          PULONG ReturnLength);

HMODULE hMod = LoadLibrary(_T("NtDll.dll"));
 NtQueryObjectPtr QueryObj = (NtQueryObjectPtr)::GetProcAddress(hMod, "NtQueryObject");
 ASSERT(QueryObj);

ULONG OutSize = 0;
 NTSTATUS NtStatus = QueryObj(hHandle, ObjectTypeInformation, NULL, 0, &amp;amp;amp;OutSize);
 PPUBLIC_OBJECT_TYPE_INFORMATION TypeInfo = (PPUBLIC_OBJECT_TYPE_INFORMATION)calloc(1, OutSize);
 ULONG InSize = OutSize;
 NtStatus = QueryObj(hHandle, ObjectTypeInformation, TypeInfo, InSize, &amp;amp;amp;OutSize);
 TypeName = TypeInfo->TypeName.Buffer;
 free(TypeInfo);
}
// This is how we invoke the function note: GetCurrentProcess() call.
CString cs;
GetHandleTypeName(GetCurrentProcess(), cs);
MessageBox(cs);
Feb 172009
 

Use following functions

  1. _strupr
  2. _strlwr
  3. std::transform – does the trick too but hard to understand
/* STRLWR.C: This program uses _strlwr and _strupr to create
 * uppercase and lowercase copies of a mixed-case string.
 */

#include <string .h>
#include <stdio .h>

void main( void )
{
   char str[100] = "The String to End All Strings!";
   printf( "Mixed: %s\n", str );
   printf( "Lower: %s\n", _strlwr( str ));
   printf( "Upper: %s\n", _strupr( str ));
}

// Output
// Mixed: The String to End All Strings!
// Lower: the string to end all strings!
// Upper: THE STRING TO END ALL STRINGS!

How about converting std::string to upper or lower case?

// Convert std::string to upper or lower case
std::string teststr = “Nibu Babu Thomas”;
_strlwr( &teststr[0] );
cout << endl << teststr.c_str() << endl; _strupr( &teststr[0] ); cout << teststr.c_str() << endl;[/sourcecode] How about converting 'CString' to upper or lower case? Fortunately and wisely enough there are member functions called 'MakeLower', 'MakeUpper'. Phew! [sourcecode language='cpp']CString csTest = _T( "Nibu Babu Thomas" ); csTest.MakeUpper();// Now in upper case csTest.MakeLower(); // Now in lower case[/sourcecode]

Feb 062009
 

For this purpose we use _kbhit function included in conio.h file. Please note that conio.h is a non-standard header file so can’t say if _kbhit will be available in other libraries. The purpose of  _kbhit is to check whether a key has been hit and so then we can use this function to wait till a key is pressed. To know which key is pressed we can use _getch or _getche functions immediately after a call to _kbhit. _kbhit returns TRUE if a key is pressed else returns FALSE.

Internally _kbhit used PeekConsoleInput windows console API to check whethere is a KEY_EVENT in input queue. If there is one then it returns TRUE. Note that _kbhit peeks on all events from input queue to check whether there is a KEY_EVENT. Note that extended keys are ignored!

Here are some functions to demonstrate the power of _kbhit

  1. ClearInputBuffer – Clears key events from input buffer using _kbhit
  2. Pause – Much like window’s ‘Pause’ command, except for the animation of ellipses.

#include
#include

void ClearInputBuffer()
{
   while( _kbhit() )
   {
      // Read and ignore chars from input buffer resulting in removal from input buffer
      _getch();
   }
}

void Pause( const char* Msg = NULL )
{
   std::cout << ( Msg ? Msg : "Press a key to continue" );    const int EllipsesCount = 3;    const char* MoveBackChars[EllipsesCount] = { "\b", "\b\b", "\b\b\b" };    const char* AllClearText[EllipsesCount] = { " ", "  ", "   " };    const char* Ellipses[EllipsesCount] = { ".", "..", "..." };    int ActiveEllipsesIndex = 0;    while( true )// Animate until a key is pressed    {       std::cout << Ellipses[ActiveEllipsesIndex];       Sleep( 500 );       if( !_kbhit() )       {          std::cout << MoveBackChars[ActiveEllipsesIndex];          std::cout << AllClearText[ActiveEllipsesIndex];          std::cout << MoveBackChars[ActiveEllipsesIndex];       }       else       {          _getch();          break;       }       ActiveEllipsesIndex = (ActiveEllipsesIndex + 1) % EllipsesCount;    } } int main( void ) {    ClearInputBuffer();    Pause();    return 0; }[/sourcecode]

Aug 012008
 

If you are not careful while using sscanf and fscanf, you code could lead to stack corruption errors leading to application crash.

Recently when migrating a project in VC6 to VC8, a similar situation arose, I was getting stack corruption errors…

“Run-Time Check Failure #2 – Stack around the variable ‘ByteVar’ was corrupted.”

So I started looking for usage of “ByteVar” in the code being migrated, so a particular innocent looking piece of code got my attention and looked something like this…

BYTE ByteVar = 0; // Declaration
sscanf( Buffer, "%d", &ByteVar );// Looks innocent right?

But the problem here is with the format specifier used for a BYTE var, it should be %c, but it’s %d i.e. sscanf reads in 4 bytes instead of 1 byte but the address passed in is of a BYTE. 🙁

In release this works fine and in debug mode above error pops up. Trouble is how to fix this, it’s dangerous to change %d to %c because sscanf will read in only 1 byte instead of four bytes which will result in invalid data being read into other variables. So the safest option IMO is to change the type of “ByteVar” from BYTE to int.

Jul 072008
 

Let’s suppose you wanna create a typedef for a fixed length array, so first thing that you would do is this…

typedef char[100] HundredChars;

This will not work as typedefing an array requires different syntax, here is how we do it…

typedef char HundredChars[100];