2011-07-30 91 views
2

我在代码中遇到问题,无法弄清楚。我有三个线程,线程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; 
} 
+0

一个不好的多线程示例... – Ajay

回答

3

如果lParam0,调用_itoa(num, str, 16)将导致单个字符的字符串"0"

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

更一般地,范围从015(含)的lParam的值将触发该问题。

+0

C没有负数索引到数组中。只是说'... – pezcode

+0

@pezcode,数组索引是指针算术,指针算术是有符号的。看[这个答案](http://stackoverflow.com/questions/3174850/type-for-array-index-in-c99/3174900#3174900)。 –

+2

@pezcode:C数组索引只是'*(E1 + E2)'的语法糖,其中一个表达式是指针类型,另一个是整型,所以像'(-2)[“hello” + 2]'完全有效并且定义为C. – ninjalj