线程堆栈错误

时间:2011-07-30 10:54:56

标签: c++ c windows winapi

我的代码出现问题,无法解决问题。我有三个线程,线程1以十六进制输入两个数字,线程2和3用前两个数字交换前两个数字并打印结果。

错误讯息:

  

运行时检查失败#2 - 变量'str'周围的堆栈已损坏。

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;
}

1 个答案:

答案 0 :(得分:3)

如果lParam0,则调用_itoa(num, str, 16)将生成单字符字符串"0"

在这种情况下,i将为1,而str[i - 2] = a将在字符串之前写入,从而破坏堆栈。

更一般地说,从lParam0(包括)的15值会引发问题。