Link to home
Start Free TrialLog in
Avatar of alexatsearidge
alexatsearidgeFlag for Canada

asked on

TCHAR initializes with garbage data.

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();
Avatar of alexatsearidge
alexatsearidge
Flag of Canada image

ASKER

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."
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>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)