views:

37

answers:

2

Hello everyone. It seems I figured out most of my problems by simply multi-threading my application! However, I am running into a little bit of an error: "Stack around variable 'x' was corrupted." It works properly (after hitting abort on the Debug Error), but obviously I cannot have an error everytime someone runs the application. So here is the relevant code. It is the callback to one of my worker threads.

DWORD WINAPI Arc_writePipe(LPVOID threadParam)
{
    Arc_Redirect ar;
    DWORD dwWrote;
    CHAR chBuf[BUFSIZE];
    HANDLE hPipe = (HANDLE)threadParam;
    HWND g1   = FindWindow("GUI",NULL);
    HWND dlg  = GetDlgItem(g1,IDO_WORLDOUT);
    //int nLength = GetWindowTextLength(GetDlgItem(g1,IDO_WORLDINPUT));

    while(bRunThread)
    {
        if(GetDlgItemText(g1,IDO_WORLDINPUT,chBuf,BUFSIZE))
        {
            chBuf[BUFSIZE] = '\0';
            if(!WriteFile(hPipe,chBuf,BUFSIZE,&dwWrote,NULL))
            {
                //SetDlgItemText(g1,IDO_WORLDINPUT,NULL); // This is to reset text when done sending to input
                if(GetLastError() == ERROR_NO_DATA)
                    break; // Normal :)
                else
                    MessageBox(g1,"Error: Could not WriteFile();","Error",MB_ICONERROR);
            }
        }
    }
    return 1;
}

Does anyone have any ideas on why this error keeps occurring? I am not getting any GetLastError() output other than "ERROR_NO_DATA," after the data is written so I am assuming it has something to do with my WriteFile(); function in conjunction with the BUFSIZE (defined at 0x1000). So basically, I am doing something wrong. Does anyone know perhaps a better way to get information from an edit dialog and write it to a pipe?

Thanks so much for your help!

Regards,
Dennis M.

+2  A: 

I don't know where the corruption is happening, so I don't know what exactly the problem is. However, the following line is wrong:

chBuf[BUFSIZE] = '\0';

You declared chBuf with the size BUFSIZE which means that the index BUFSIZE is actually outside of the array. This will result in stack corruption. What you really need to do is chBuf[BUFSIZE - 1] = '\0';

JSBangs
+2  A: 

In addition to indexing the array beyond the end as JS Bangs pointed out, you also probably don't want to be writing the entire chBuf to the pipe, as you are currently writing out the null terminator as well as any garbage that fills up the rest of the array past the end of the string. You may want to check the length of the string that you retrieved and write only that amount.

Brook Miles