How to check whether the Pointer is allocated in Stack or Heap in Debug?

14 12 2008


What if you call delete operator by using a stack pointer? Like that, while writing frameworks sometimes we expects the pointer that gets passed to the function should point a valid memory block which is allocated on heap itself. So how can we check whether the pointer points to stack or heap in debug version?

stackorheap


You can use the function - _CrtIsValidHeapPointer(). Its an undocumented CRT function. But it works only in debug version. Well, please check the code snippet below,

#include "malloc.h"
...

// Check heap pointer.
int* pInteger = new int;
BOOL bHeap = _CrtIsValidHeapPointer( pInteger );

// Check stack pointer and you'll get an assertion.
char CharArray[100];
bHeap = _CrtIsValidHeapPointer( CharArray );


Its annoying that its not available in release version. Well, atleast we could make our framework to notify the user while debugging in the debug build. isn’t it?


Targeted Audience - Beginners.





Watch byte streams in Memory Window more easily.

13 11 2008


Assembly programming! It fascinates me always. I love sending packets of data to hardware, parsing back the replies, etc. You might be using BYTE arrays for doing such stuffs. well, in that case, instead of watch window, memory window is preferable to see the byte stream, because it will be so easy to see the entire message.

For instance, assume that we need to send a packet of data in following format.
memorywindow1

Following code snippet generates similar array. Ofcourse in legacy coding style.

// Data packet.
const int DATA_PACKET_LEN = 12;
BYTE DataPacket[DATA_PACKET_LEN] = { 0 };

int Index = 0;

// Add the first DWORD.
DataPacket[Index] = 1;
Index += sizeof( DWORD );

// Add the second WORD.
DataPacket[Index] = 2;
Index += sizeof( WORD );

// Add the third WORD.
DataPacket[Index] = 3;
Index += sizeof( WORD );

// Add the forth DWORD.
DataPacket[Index] = 4;
Index += sizeof( DWORD );

If you watch DataPacket in memory window, it will look like this.
memorywindow2
A chunk of bytes. It seems hard to read and interpret values. isn’t it? More over that, in intel machines, the values are stored in LSB format which makes the readability even more worse. well is there any trick which helps to read the format even better.


If you right click in the Memory window, you’ll get the context menu and in that you can select the preferred byte ordering.
memorywindow3

Select “Long Hex Format” to group bytes as DWORDs. Well, now you can read the byte stream, as such in the packet format picture. cool! isn’t it?
memorywindow4


Yes! i know. You’re thinking about this - the second and third parameter get swapped. Well, its due to the fact that Intel machines follows LSB layout for storing values in memory. This is not perfect solution but it does make life easier and having something is better than nothing! isn’t it? ;)


Targeted Audience - Intermediate.





How to kill process in batch by using wildcard filters?

24 10 2008

I often get irritated while working in huge frameworks. A lot of application might be running simultaneously and it fills up my task bar. Usually I drag and adjust my taskbar, 3X more taller than usual. But still they fill up my taskbar. Most of them were servers running in command prompts or executable have some common prefix and Its a real burden while closing all windows. I’ve to close them one by one. Is there any command gun to kill them all in one shot? ;)


You could use the command taskkill. Have a look at the syntax.

Syntax: taskkill /IM <ExeName>
E.g.
C:\>taskkill /IM note*
SUCCESS: The process "notepad.exe" with PID 2428 has been terminated.
SUCCESS: The process "notepad.exe" with PID 3588 has been terminated.
SUCCESS: The process "notepad.exe" with PID 4960 has been terminated.
SUCCESS: The process "notepad.exe" with PID 3320 has been terminated.
SUCCESS: The process "notepad.exe" with PID 4704 has been terminated.


Note that taskkill command is available from Windows XP onwards. So take care.


Targeted Audience - Beginners.





I’m Back Again!!!

3 10 2008

Guys,

Life! Everything that happens are so unexpected. During last few weeks, me too had some unexpected encounters in my personal life. The bad news is, during those days, I couldn’t make Weseetips alive. :( Well, the good news is, at last I’ve overcame the barriers and am smiling now! :D Now I am back to business! I thank my fellow readers for being patient. Yes! Lets rock on…





how to set color for static control text in dialog?

27 08 2008


Colors convey meanings too. For instance, if something is written in red - that means something to be cautious. If its in green, its treated as safe. Well, usually in window dialogs, the static control texts are black in color. Is it possible to color them to convey more meaning?


Yes! You have to handle WM_CTLCOLOR message. For each control, this message will be triggered and you’re free to do modification on your control. Have a look at the code snippet in MFC framework.

// Message Map
BEGIN_MESSAGE_MAP(CDlgDlg, CDialog)
    ...
    ON_WM_CTLCOLOR()
END_MESSAGE_MAP()

HBRUSH CDlgDlg::OnCtlColor( CDC* pDC, CWnd* pWnd, UINT nCtlColor )
{
    // Call base class version at first. Or else it will override your changes.
    HBRUSH hbr = CDialog::OnCtlColor( pDC, pWnd, nCtlColor );

    // Check whether which static label its.
    if( pWnd->GetDlgCtrlID() == IDC_STATIC_OK )
    {
        // Set color as red.
        pDC->SetTextColor( RGB( 255, 0, 0 ));
        pDC->SetBkMode( TRANSPARENT );
    }

    return hbr;
}


Always call CDialog::OnCtlColor() at first. Or else it will override your modifications.


Targeted Audience - Intermediate.





How to calculate the checksum of data?

5 08 2008

Long back, I own a Cyrix machine and periodically it stops booting by showing the message - “Checksum failure“. I still remember those long beeps. :) Well, Checksum is digest generated from a long data which can be used to check the integrity of data.

For instance, if you want to know whether your data file is corrupted, generate and keep the checksum and afterwards for verification again generate the checksum and compare. So how to generate the checksum?


You can use the function - CheckSumMappedFile(). Actually its used to calculate the checksum of mapped file. Well, you can use it to calculate the checksum of your data too! Just see the code snippet.

// The data.
char* pString = "Hello";
DWORD HeaderSum = 0;
DWORD Checksum = 0;

// Calculate the checksum.
CheckSumMappedFile( pString,
                    strlen( pString),
                    &HeaderSum,
                    &Checksum );


The return of the function is PIMAGE_NT_HEADERS and in this case, it will be 0 and just ignore it. Since our data provided is not a valid PE file, its obvious. If you check the Checksum variable, you can find it contains a valid checksum always. So Take care!


Targeted Audience - Intermediate.





How to identify the module load order?

13 07 2008


When an application starts, windows loads the necessary dll files to the system memory - “in required order”. But how to get the dll load order of perticular application? You’ve already seen - When we start the application via debugger, it will output the module load order info to the watch window. Have a look at it,

Loaded 'ntdll.dll', no matching symbolic information found.
Loaded 'C:\Windows\System32\kernel32.dll', no matching symbolic information found.
Loaded 'C:\Windows\System32\dbghelp.dll', no matching symbolic information found.
Loaded 'C:\Windows\System32\msvcrt.dll', no matching symbolic information found.
Loaded 'C:\Windows\System32\advapi32.dll', no matching symbolic information found.
Loaded 'C:\Windows\System32\rpcrt4.dll', no matching symbolic information found.
Loaded 'C:\Windows\System32\mfc42.dll', no matching symbolic information found.
Loaded 'C:\Windows\System32\user32.dll', no matching symbolic information found.
Loaded 'C:\Windows\System32\gdi32.dll', no matching symbolic information found.

Seems Good! But, is there any easy method?


Yes! Take menu item, Debug -> Modules. And it will show the dialog of all loaded modules. By default the modules are sorted in load order. See the screenshot.


Now you don’t need to jump into that watch window for searching the module load order. ;)


Targeted Audience - Beginners.





How to restrict mouse cursor inside window?

1 07 2008


every windows application is a citizen of Windows OS and the mouse is shared between them. If your applications shows some critical dialog to get response, but its quite possible that your dialog can be skipped by user and take another application window. How can you restrict the mouse cursor inside your application window?

For instance, the following application - CursorJail. How can you close your mouse pointer into the dialog prison?


You can use the api - ClipCursor(). See the following code snippet.

// Get window rect.
RECT WindowRect;
GetWindowRect( &WindowRect );

// Restrict the cursor
ClipCursor( &WindowRect );
...
// Free the cursor.
ClipCursor( 0 );

Well, need the code snippet for drawing prison? ;)

// Get client rect.
CRect ClientRect;
GetClientRect( &ClientRect );

const int SteelBarCount = 5;
int xOffset = ClientRect.Width() / SteelBarCount;

dc.Draw3dRect( 0,0, ClientRect.Width(), ClientRect.Height(), 0, 0 );
// Draw steel bars.

for( int SteelBarIndex = 1; SteelBarIndex < SteelBarCount; ++SteelBarIndex )
{
    dc.MoveTo( xOffset * SteelBarIndex, 0 );
    dc.LineTo( xOffset * SteelBarIndex, ClientRect.Height());
}

dc.MoveTo( 0,0 );
dc.LineTo( ClientRect.Width(), ClientRect.Height());


You can use this clip feature to restrict the cursor between different dialogs of same application. You can hide a lot of GUI bugs. Try it ;)


Targeted Audience - Beginners.





Allocate CString on heap - Does that saves memory and improve performance?

24 06 2008

“Objects - The stack’s worst enemy. The stack is only indented for light weight datatypes such as int, float etc. So if you want to allocate a lot of objects, allocate on Heap. Or else stack will overflow”

This is the golden rules that beginners learn first, while stepping into professional C++ development. While considering objects, CString instances are the most common ones used in almost all MFC applications and for improving performance and for saving memory, usually we used to allocate it on heap. But, does that saves memory and improve performance? Well, its a myth. Want to know why?


First of all check the following code snippet and answer me, whether the message box will be shown or not?

// CString size == int size?
if( sizeof(CString) == sizeof(int))
{
    // I can't believe it.
    AfxMessageBox(_T("Am I dreaming?"));
}

Yes! It’ll be shown and the size of CString is just 4 bytes. Actually CString just contains LPTSTR as member. CString always allocate the string on heap. So while allocating CString itself on heap, you’re really degrading performance by extra heap allocation and more over you’ve to manage the pointer which can lead to memory leaks.


Don’t think that all objects are good candidates for heap. There can be exception like our CString. ;)


Targeted Audience - Intermediate.





How to add ampersand(&) symbol to dialog control captions?

15 06 2008


For dialog controls we can assign keyboard accelerators. If you give the button text as “&Add”, then really it will become Add” because the ampersand character is used to mark the keyboard accelerator for that control. But what to do if you want the button text to be “Add & Refresh“?


Just use && if you want ampersand as part of caption instead of Keyboard accelerator marker. For instance see the screenshot.


Targeted Audience - Beginners.