Search code examples
c++multithreadingwinapiwritefile

WinAPI Write "Edit" Dialog to Pipe (Error: Stack around variable 'x' was corrupted)


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.


Solution

  • 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';