Thread stack error
I am having a problem in my code and am unable to figure it out. I have three threads, thread 1 takes input of two numbers in hex, thread 2 and 3 exchange these first two digits with the last two and print the result.
Error message:
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.....开发者_如何学JAVA.\n ");
return TRUE;
}
If lParam
is 0
, calling _itoa(num, str, 16)
will result in the single-character string "0"
.
In that case, i
will be 1
, and str[i - 2] = a
will write before the string, thus corrupting the stack.
More generally, values of lParam
ranging from 0
to 15
(inclusive) will trigger the problem.
精彩评论