我的代码有问题,但无法解决。我有三个线程,线程 1 接受两个十六进制数字的输入,线程 2 和 3 将前两位数字与后两位数字交换并打印结果。
错误消息:
Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted.
DWORD WINAPI changevalue( LPVOID lpParam )
{
WaitForSingleObject(inThread,INFINITE); //Input thread
printf("thread 1 and 2 running \n");
int num = 0;
num = (int)lpParam;
int i = 0;
char str[10] ={0};
char a,b;
_itoa(num,str,16);
while (str[i] != NULL)
{
i++; //Get location of last char..
}
//Exchange first two digits with last two.
a = str[0];
b = str[1];
str[0] = str[i-2];
str[1] = str[i-1];
str[i-2] = a;
str[i-1] = b;
printf("num=%s\n",str);
//long numl=strtol(str,&stop,16);
//printf("num = %x\n", numl);
//We can also take input to a string then manuplate it, and
//then print it in form of a string only.
//But int is used since it is mentioned in the statement.
printf("thread 1 and 2 exit......\n ");
return TRUE;
}
最佳答案
如果lParam
为0
,调用_itoa(num, str, 16)
将得到单字符字符串"0”
。
在这种情况下,i
将是 1
,并且 str[i - 2] = a
将写在之前 字符串,从而破坏堆栈。
更一般地说,lParam
的值范围从 0
到 15
(含)都会触发问题。
关于c++ - 线程堆栈错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6882676/