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?
Than开发者_运维知识库ks so much for your help!
Regards,
Dennis M.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';
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.
精彩评论