Tuesday, December 7, 2010

CRT Debug support: Memory values

Tip - Debug heap will fill some values in memory which is managed. By checking the memory values of an address, we are able to identify the characteristic of memory allocation details.

Details - Memory corruptions are every programmer’s nightmare. But Debug Heap provides some facility in debug build to help you to get rid of those memory corrupting problems. Depending to the type of memory allocation we have done, the debug heap will fill some magic value for the allocated memory contents. Take care that, this will be available only in debug build. Please see below.
1.     0xCD – The memory locations filled with this magic number are allocated in heap and is not initialized.
2.     0xFD – This magic number is known as “NoMansLand”. The debug heap will fill the boundary of the allocated memory block will this value. If you are rewriting this value, then it means, you are beyond an allocated memory block.
3.     0xCC – The memory locations filled with this magic number means, it’s allocated in stack but not initialized. You can see this when you a variable on stack and look at its memory location. You can use /GZ compiler option to get the same feature in release build.
4.  0xDD – The memory locations filled with this magic number are Released heap memory.  But when I checked I am getting 0xEEFE(freed memory pattern) always instead of 0xDD.

Reference    :

Posted By :Krishnaraj S.

Memory Leak Detection and Isolation - Part2: Set Breakpoints on a Memory Allocation Number

Tip - To identify which allocation in code causing memory allocation even we know line number and function name.
Details - Sometimes you know the line number and function name of the code which cause memory leak. But it can be executed several times and often it is difficult to track which and when allocation cause memory leak. The piece of information that allows you to do this is the memory allocation number. This is the number that appears in braces after the filename and line number when those are displayed. For example, in the following output, the memory allocation number is 109. It means that the leaked memory is the 109th block of memory allocated in your program.
The CRT library counts all memory blocks allocated during execution of the program, including memory allocated by the CRT library itself or by other libraries such as MFC. Therefore, an object with allocation number N will be the Nth object allocated in your program but may not be the Nth object allocated by your code. (In most cases, it will not be.)
If you can set the break point at the memory allocation number in you program, your debugger can break the execution at particular break point and is able to debug wisely to track the memory leak.


Fortunately CRT library provides you the methods to set break point at  memory allocation number. Two methods are described below.

Using _CrtSetBreakAlloc():
Call _CrtSetBreakAlloc(AllocationNumber); in your code.

Using Watch window of visual studio debugger:
Type ‘_CrtSetBreakAlloc’ in the name field of watch window. Type ‘{,,msvcr71d.dll}_crtBreakAlloc’ for multithreaded dll version of CRT library(/MD option).
After debugger evaluate the expression, edit the value field with memory allocation number to set the breakpoint.




Reference    :

Posted By :Krishnaraj S.

Memory Leak Detection and Isolation - Part1: Enabling MemoryLeakDetection

Tip - Visual Studio debugger and C run-time (CRT) libraries provide you with effective means for detecting and identifying memory leaks.
Details -The primary tools for detecting memory leaks are the debugger and the C Run-Time Libraries (CRT) debug heap functions.
To enable the memory leak detection on heap, add following piece of code in your program. For this make sure that your code is _DEBUG enabled.
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
Next step is to insert _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ) to your main function of your application.
 
Now your application is ready to detect memory leak and it will display the logs in output window of your debugger or use Dbgview.exe . For release version, you required to enable _DEBUG preprocessor. A sample log look like as below.
 




Technique behind this is to use _malloc_dbg() and _free_dbg() instead of malloc() and free(). So that it is able to keep track of memory allocation and deletion. When we use CRT debug methods, compiler will use _malloc_dbg() and _free_dbg() for heap managing.
Note: You can manually dump the log using _CrtDumpMemoryLeaks() API. But remember that the destructors for any variables you declared at runtime (i.e. any variables declared not using the 'new' operator) have *NOT* been called yet. This makes the memory holding these variables look like leaked memory when in fact the memory will be cleaned up just prior to program exit. So highly recommended method is to use _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
 
Reference    :

Posted By :Krishnaraj S.

Cancelling the file copy

Tip - Use CopyFileEx if the file copy is supposed to be cancelled/stopped conditionally.
Details  -
CopyFileEx provides an option to register progress call-back during the copy operation. And the return value of this call-back function can be used to  control  the copy operation. This API is useful for the graceful exit of application threads on application closure, rather than leaving the files being copied in an undefined state.

The table below shows relevant return values for the call-back function. We can control the copy operation by using these values.


Return code/value
Description
PROGRESS_CANCEL
Cancel the copy operation and delete the destination file.
1
PROGRESS_CONTINUE
Continue the copy operation.
0
PROGRESS_QUIET
Continue the copy operation, but stop invoking the call-back to report progress.
3

PROGRESS_STOP
Stop the copy operation. It can be restarted at a later time.
2


Reference         -

Posted By :Praveen E

Relative paths and multithreaded applications

Tip   - Using relative paths in multi-threaded applications can create unpredictable results
Details -
The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. Using relative path names in multithreaded applications or shared library code can cause unpredictable results, when some code portion sets the current directory.  

This limitation also applies to the GetCurrentDirectory and GetFullPathName functions. Similarly, the common file dialog changes the current directory when we navigate  the file system using the file dialog; unless otherwise we specify OFN_NO­CHANGE­DIR flag. Finally, the parent application which created the common file dialog will end up with a current directory that the developer never dreamt of. So, do not assume that “current directory = application directory”. It depends on the APIs used, implicit behaviors like  in  common file dialog etc.

          LPSTR lpszDir = new TCHAR[100];
          GetCurrentDirectory( 100, lpszDir );
          CFileDialog dirChanger( TRUE );
          dirChanger.DoModal();
// Do some maneuvers with myDirChanger dialog. Navigate to other folders.
          GetCurrentDirectory( 100, lpszDir );

In the above example, the two GetCurrentDirectory() calls return different paths. That means, the "." refers to entirely different locations before and after the CFileDialog usage.

To conclude:
1.    Be careful to use relative paths in multi-threaded applications.
2.    Avoid the usage of “SetCurrentDirectory” in multi-threaded applications.
3.    The path returned by “GetCurrentDirectory” may not be the path where the application is located.

Reference         -

Posted By :Praveen E

Rational Purify: recommended settings

Tip  - Purify'd application crashes often . There are many recommended methods to make the purify application to do  the real  job.  
Details  -
1. Build with the Recommended Microsoft Visual Studio settings. ( http://www-01.ibm.com/support/docview.wss?us=993&uid=swg21265414 )
2. Stop unnecessary processes on your system. Some unrelated process running on the system could cause this problem. Antivirus software is a common process that causes problem with PurifyPlus. Other background processes, such as one for dual-monitor display, could cause the problem, as well.
3. Instrument third party modules in Exclude mode. There may be a third party module that behaves unexpectedly when instrumented. You can instrument those modules in Exclude mode to try to get past the error.
4. Remove the <exe>_pure.ini file. Purify generates an ini file (used for storing Purify settings for that executable) named after the executable being instrumented.

Reference         -


Posted By :Praveen E

SHFileOperation – All in one file management API

Tip  - It can do many things; Copy, move, rename, or delete file system object(s). 
Details  -

·         SHFileOperation can handle different file management operations; Copy, move, rename, or delete. 
·         It can do operations on multiple files in a single execution.
·         It can copy security attributes; CopyFile or CopyFileEx cannot copy the security attributes of the source to destination while file attributes can be copied.
·         It can display a progress dialog similar to the windows copy dialog, based on specific flags.
·         There is no direct progress call-back option. CopyFileEx allows specifying a call-back pointer which will get invoked periodically.
·         GetLastError() API cannot be used to detect the errors while executing SHFileOperation.
·         You can delete the file keeping it in recycle bin, by specifying the FOF_ALLOWUNDO flag.
·         File deletion can be made recursive.
·         Operations on multiple files use the double-null terminated format.
·         And so on; it suits most of the file operations generally carried out programmatically.


Reference          


Posted By :Praveen E