2013-03-21 45 views
1

我寫了一個程序來創建10個線程並正常運行。該程序運行良好,但最終會出現分段錯誤。這是什麼故障,是什麼原因造成的,我該如何解決? 我的代碼是:程序執行期間的分段錯誤

#include<stdio.h> 
#include<pthread.h> 
void *print(void *num); 

int main() 
{ 
    pthread_t tid[10]; 
    int n,check; 
    void *exitstatus; 
    for(n=1;n<=10;n++) 
    { 
     check=pthread_create(&tid[n],NULL,print,(void *)&n); 
     if(check=0) 
      printf("thread created"); 
     pthread_join(tid[n],&exitstatus); 
    } 

    return 0; 

} 

void *print(void *num) 
{ 
    int i,*val=(int *)num; 
    for(i=0;i<(5);i++) 
     printf("Hello World!!!(thread %d)\n",*val); 
} 
+0

您是否嘗試過使用gdb來隔離錯誤的來源? – ziu 2013-03-21 12:41:57

回答

8

你有很多缺點:

for(n=1;n<=10;n++) // No, The array starts from 0 and lasts on 9 

試試這個

for(n=0;n<10;n++) 

if(check=0) // No, this will assign 0 to check instead of compare it 

試試這個

if(check==0) 
+0

如果我們初始化n從1而不是0 – user3032010 2013-03-21 12:49:23

+0

@kanika,爲什麼會出現這個錯誤,因爲C和其他C語言中的數組從0開始索引 – 2013-03-21 12:52:11

3

您正在訪問超出其索引的數組。這是未定義的行爲。

您的陣列t[10]開始在指數t[0],並應在t[9]結束 -

for(n = 0; n < 10; n++) { 
//your stuff 
} 

而且check == 0是你如何檢查平等。 check = 0將分配給0check

所以,你的代碼必須是這樣的:

#include<stdio.h> 
#include<pthread.h> 
void *print(void *num); 

int main() 
{ 
    pthread_t tid[10]; 
    int n,check; 
    void *exitstatus; 
    for(n = 0; n < 10; n++) 
    { 
     check=pthread_create(&tid[n], NULL, print, (void *)&n); 
     if(check == 0) 
      printf("thread created"); 
     pthread_join(tid[n], &exitstatus); 
    } 
    return 0; 
} 

void *print(void *num) 
{ 
    int i,*val=(int *)num; 
    for(i = 0; i < 5; i++) 
     printf("Hello World!!!(thread %d)\n", *val); 
} 

另外要注意的編程風格:請使用正確的縮進和空白明智地使用。如果使用正確的縮進和空格,大多數編程錯誤和錯誤都可以消除。例如,在for循環中的運算符之前和之後的一個空白區域,以及在,之後和下一個參數之前調用函數時的參數之間的一個空白區域。

+0

一個說明 - SEGFAULT(段錯誤)是指程序訪問的內存地址是該程序無效。這個程序訪問數組的末尾是一個很好的例子。請注意,C這種方式很糟糕。如果在數組結束後有有效的內存,那麼使用'&tid [n]'就會起作用,將結果寫在其他可能有用的內存上,從而產生垃圾。 – ash 2013-08-25 05:14:09