STL valarray – An easy way to manipulate values.

25 04 2008


Assume you need to find the sum of 100 integers. You can create an array or use some STL containers, fill the values and by iterating you can find the sum. Instead of that you can use valarray container for storing any value type and do a number of mathematical operations for all items in just a function call.


See the code snippet for how to use valarray.

// Integer array of 10 members.
valarray<int> IntegerArray( 10 );

// Filling the array.
for( int nIndex = 0; nIndex < 10; ++nIndex )
{
    IntegerArray[ nIndex ] = nIndex;
}

// I need to get the sum of all number.
int nSum = IntegerArray.sum();

If you want to manipulate bulk amount of numbers, better use valarray.


The valarray contains only sum() and misc functions are its member function. Still they are useful, if you want to keep bulk amount of numerals.


Targeted Audience – Beginners.

Advertisements




Assertion while calling set_new_handler(). Why?

23 04 2008


C++ allows us to set a exception handling function, to handle memory allocation failures. When ever memory allocation failure occurs, this function will be called. See the following code block.

// Memory allocation error handler.
void __cdecl MyNewHandler()
{
    std::cout << "Allocation failed.";
}

void main()
{
    // Set the new handler
    set_new_handler( MyNewHandler );

    int *pi = new int[500000000];
}

Its valid, it calls the function to register the memory allocation failure handling function and it compiles. Perfect! But when you run it, it will show assertion. Do you know why?


You’ve missed an underscore. Yes, i really mean it! Actually the function you’ve to call for registering “new handler” is _set_new_handler(), not the set_new_handler(). The set_new_handler() is just a stub function, which is provided in the C runtime library to compile the STL. Its not indented to be used by us. See the correct usage of _set_new_handler() below.

#include <iostream>
#include <new.h>

// Memory allocation error handler.
int MyNewHandler( size_t size )
{
    std::cout << "Memory allocation failed!";
    return 0;
}

void main()
{
    // Set the new handler
    _set_new_handler( MyNewHandler );

    int *pi = new int[500000000];
}


This often happens when you use third party application such as Visual Assist for improved intellisense. The function it auto completes can be an existing one, but may waste several hrs of effort. isn’t it? 😉


Targeted Audience – Advanced.





How to take command Prompt with default path as Selected Folder Path.

22 04 2008


Usually in huge frameworks, we’ve to run a lot of console applications for starting up the system. Sometimes we’ve to start it by specifying long commandline arguments. In those cases, instead of double click and running the application, usually we take command prompt and start applications by entering commandline.

When, Console opens, it points to the default path and we’ve change the directory to required folder by CD command. Is there any easy way to start command prompt with default path as selected folder in Windows explorer? Yep! there is.


Just do the following steps.

1) Take Windows explorer.
2) Take Tools > Folder options.
3) Take File Types tab.
4) Select “Folder” Filetype.
5) Click advanced.
6) Click “New
7) Now give Action: “Cmd” and application used to perform action as “cmd.exe
8 ) Now, click ok in all dialogs.
9) Now press WinKey+E to see the windows explorer.
10) Now right click on any of the folders in tree and you can see the menu item cmd.
11) Now click on that, a new console will be opened with default path as selected folder’s path.


Targeted Audience – Beginners.





How to create NTFS File links Programmatically.

21 04 2008


Unix guys don’t need an introduction about file links, because its one of the beginner Unix skills – how to create a file link. But usually in windows arena, file links may be the least discussed one among beginners. In simple words, file links are – one Physical file in disk but with different file names. All the file names points to the same file. There are a number of usages for file links.

  • Hide the master file from a bunch of naughty users.
  • You can assign different access rights for different users by creating file links for the same file.( each link have different permissions.)
  • To keep the filename constant and you can change the mapping to another file.
  • Etc etc… it goes on.


So how can i create a link for a file? You can use the api – CreateHardLink(). See the sample code snippet below.

CreateHardLink( _T(“c:\\masterfile.dat”),    // Source File
                _T(“c:\\LinkToMaster.dat”),  // Link name
                NULL );    // Security attributes


You can use DeleteFile() to delete the created link.


Targeted Audience – Beginners.





Use throw; carefully. Or else, Unhandled exception will be the result.

20 04 2008


Usually throw; is used to rethrow the exception object. But you should be careful. If you call throw; where there is no exception object in the context, then it will result an un-handled exception and abnormal program termination. The interesting part is that, even catch(…) cannot catch such exceptions.


See the sample code snippet below.

try
{
    throw;
}
catch( ... )
{
}

So take care next time.


Targeted Audience – Intermedite.





How to find the source filename and line no. from memory pointer in debug version.

19 04 2008


It will be nice, if its possible to find out the source filename and line number where the pointer is allocated by just using the memory pointer itself. Yes its possible! But only in debug version.


When you call new, the c runtime library allocates the memory and returns the pointer. But infront of the given pointer, one CRT MemoryBlock Header is secretly kept in debug version. see the declarations of Debug MemoryBlock header below.

typedef struct _CrtMemBlockHeader
{
struct _CrtMemBlockHeader * pBlockHeaderNext;
struct _CrtMemBlockHeader * pBlockHeaderPrev;
char *                      szFileName;
int                         nLine;
size_t                      nDataSize;
int                         nBlockUse;
long                        lRequest;
unsigned char               gap[nNoMansLandSize];
} _CrtMemBlockHeader;

In this header, several information about the allocated memory block is available – such as size of memory block, source filename and line no. where the memory is allocated, whether the memory block currently in use etc etc.


From the pointer, access the MemoryBlock header. Then all these informations will be available. See the code snippet below.

// decleration of MemoryBlock header from CRT Source.
#define nNoMansLandSize 4
typedef struct _CrtMemBlockHeader
{
struct _CrtMemBlockHeader * pBlockHeaderNext;
struct _CrtMemBlockHeader * pBlockHeaderPrev;
char *                      szFileName;
int                         nLine;
size_t                      nDataSize;
int                         nBlockUse;
long                        lRequest;
unsigned char               gap[nNoMansLandSize];
} _CrtMemBlockHeader;

...

// Allocate some memory.
float* pFloat = new float[100];

// Get the memory block header.
_CrtMemBlockHeader* pMemoryBlockHeader =
    reinterpret_cast<_CrtMemBlockHeader*>( pFloat );
--pMemoryBlockHeader;

// Source File and location where the memory is allocated.
CString csSourceFileName = pMemoryBlockHeader->szFileName;
DWORD dwLineNumber = pMemoryBlockHeader->nLine;


The memory allocation is different in debug and release. isn’t it? 😉


Targeted Audience – Advanced.





How to update bulk amount of data to GUI controls without flicker.

19 04 2008


Usually for Listbox and Tree control, may be you need to add and delete thousands of entries. While doing so, its obvious that the control will flicker. It might be annoying to the user. So how can you avoid it?


You can use the api – LockWindowUpdate() and UnlockWindowUpdate() for remove the flicker while updating the UI. If a window is locked by calling LockWindowUpdate(), the the further call for getting the device context will return one with empty visible region. When you call UnlockWindowUpdate(), system invalidates the area and will send WM_PAINT. The WM_PAINT will be send only if some drawing is done to the window after locking.

You can download sample from here, which shows the difference.

See sample code snippet below.

// Lock the EditBox.
m_EditBox.LockWindowUpdate();

// Add any number of strings to it.
for( DWORD Index = 0; Index < 5000; ++Index )
{
    CString csMessage;
    csMessage.Format( _T("Item %d"), Index );

    m_EditBox.AddString( csMessage );
}

// After updating, unlock it.
m_EditBox.UnlockWindowUpdate();


Please note that, only one window can be locked at a time.


Targeted Audience – Beginners.