2011-07-30 119 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