alexatsearidge
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][][][][][][]Moz illa Firefox".
Then my copy works. So if my length were 5, windowTitle would then be "Mozil[][][][][][][][][]Mo zilla 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();
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][][][][][][]Moz
Then my copy works. So if my length were 5, windowTitle would then be "Mozil[][][][][][][][][]Mo
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();
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>>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)
>>'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)
ASKER
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."