TCHAR initializes with garbage data.

alexatsearidge
alexatsearidge used Ask the Experts™
on
Hi all, coding C++ in VS.NET 2003,

I need to look for the title of a window up to a set length.  My only problem with my code is that for some reason windowTitle gets initialized to a string that is much longer than 14.  For example, the first time my code runs lets say "Mozilla Firefox" is the window text returned.  For some reason windowTitle is initialized to "[][][][][][][bunch of garbage characters][][][][][][]Mozilla Firefox".

Then my copy works.  So if my length were 5, windowTitle would then be "Mozil[][][][][][][][][]Mozilla Firefox"
I have no idea what's going on.

-------Here's my code------------------
EnumWindowCallback.....
{
TCHAR buffer[256];
GetWindowText(hWnd, buffer, 256);

// Window we are looking for will always have the same first 14 chars
TCHAR windowTitle[14];
_tcsnccpy(windowTitle, buffer, WINDOW_TITLE_LENGTH); // Copy the first 14 chars

if (! _tcscmp( windowTitle, _T("14 chars we are looking for")) )
      DoSomething();
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
alexatsearidgeChief Architect

Author

Commented:
Ok so I forgot about the \0 at the end of the char array.  So this initializes it properly.

TCHAR windowTitle[15] = { _T("") };
windowTitle[15] = _T('\0');

However now I get an error when I run saying "Stack around the variable 'windowTitle' was corrupted."
Top Expert 2012
Commented:
The problem with '_tcsncpy()' is that it does nto NULL-terminate a string if the max length is exceeded. To ensure that this is done, you should terminate the string manually, e.g.

// Window we are looking for will always have the same first 14 chars
TCHAR windowTitle[WINDOW_TITLE_LENGTH + 1];
_tcsnccpy(windowTitle, buffer, WINDOW_TITLE_LENGTH); // Copy the first 14 chars

windowTitle[WINDOW_TITLE_LENGTH] = _T('\0'); // terminate it for sure
jkr
Top Expert 2012

Commented:
>>However now I get an error when I run saying "Stack around the variable
>>'windowTitle' was corrupted."

You are terminating 1 byte beyond the array size, make that

TCHAR windowTitle[15] = { _T("") };
windowTitle[14] = _T('\0'); // 14 is the last index, not 15

Remember, array indices are zero-based. Or use the code above ;o)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial