2013-02-24 11 views
-1

這是c中的一個簡單並行程序。並行程序中的GCC分段錯誤

我使用的是Ubuntu和gcc進行編譯。

該程序將輸入進程數量,並創建並向用戶請求相同數量的數字。 然後使用每個過程來計算每個數字的階乘。

#include<stdlib.h> 
#include<stdio.h> 
#include<sys/types.h> 

int factorial(int n) 
{ 
    int fact=1; 
    int i; 
    for(i=1 ; i<=n ; i++) 
    { 
     fact=fact*i; 
    } 
    return fact; 
} 

int main() 
{ 
    int process_id; 
    int num_process; 
    int pid; 
    int i; 

    printf("\nEnter No. of Process : "); 
    scanf("%d",&num_process); 

    int num[num_process]; 

    for (i=1; i < num_process; i++) 
    { 
     printf("\nEnter %d Number : ",i); 
     scanf("%d", &num[i]); 
    } 

    for (i=0; i < num_process; i++) 
    { 
     pid=fork(); 
     if (pid == -1) 
     { 
      perror("Error forking"); 
      return -1; 
     } 
     else if(pid > 0) 
     { 
      waitpid(-1, NULL, 0); 
     } 
     else 
     { 
      printf("\nFactorial of %d is : %d", num[i], factorial(num[i])); 
      exit(0); 
     } 

    } 
    return 0; 
} 

從未聽說過分段故障,有人可以解釋它是什麼意思?

+0

計算階乘時,不應從0開始。 – 2013-02-24 15:23:26

+1

您從未聽說過段錯誤?很難相信,因爲Google上的第一次攻擊指向:http://en.wikipedia.org/wiki/Segmentation_fault當取消引用NULL指針或讀取/寫入未分配的內存時,通常會發生段錯誤(例如,過去的末尾數組)。 – 2013-02-24 15:26:03

+1

也開始使用調試器。我喜歡gdb。 – axiom 2013-02-24 15:40:33

回答

2

此:

for (i=1; i <= num_process; i++) 
{ 
    printf("\nEnter %d Number : ",i); 
    scanf("%d", num[num_process]); 
} 

是有問題的。爲num有效的指標是0到num_process - 1.更改環路:

for (i=0; i < num_process; i++) 
2

在你factorial功能,fact沒有被初始化。也

scanf("%d", num[num_process]); 

應該是

scanf("%d", &num[num_process]); 
1

段故障的描述可以被讀取here

故障是在這裏:

scanf("%d", num[num_process]); 

因爲你是從1計數 - 陣列從零開始

此行for (i=0; i <= num_process; i++)會給你太多進程。

ALSOfork創建另一個進程 - 因此程序不平行 - 您需要使用線程。請谷歌。

+1

你不需要使用線程,你只需要正確使用'fork'。 (讓每個孩子寫出他們的輸出,而不是讓孩子回寫到父母的結果數組中。) – 2013-02-24 15:27:33