简体   繁体   English

并行程序中的GCC分段错误

[英]GCC segmentation fault in parallel program

This a simple parallel program in c. 这是c中的一个简单的并行程序。

I am using ubuntu and gcc for compiling. 我正在使用ubuntu和gcc进行编译。

The program takes input for number of processes, and creates and ask for same number of numbers from the user. 该程序输入进程数,并创建并向用户请求相同数量的数字。 Then each process is used to calculate the factorial of each number. 然后,使用每个过程来计算每个数字的阶乘。

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

Never heard of segmentation fault, can someone explain it what does it mean ? 从未听说过分割错误,有人可以解释这是什么意思吗?

This: 这个:

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

is problematic. 有问题。 The valid indices for num are 0 to num_process - 1. Change the loop to: num的有效索引是0到num_process-1。将循环更改为:

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

In your factorial function, fact is not initialized. 在您的factorial函数中, fact未初始化。 Also

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

should be 应该

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

A description of segmentation fault can be read here . 分割错误的描述可以在这里阅读。

A fault is here: 故障在这里:

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

Because you are counting from 1 - Arrays start at zero 因为您是从1开始计数-数组从零开始

This line for ( i=0; i <= num_process; i++ ) will give you too many processes. for ( i=0; i <= num_process; i++ )行将为您提供过多的进程。

ALSO fork creates another process - so therefore the program is not parallel - you need to use threads. ALSO fork创建另一个进程-因此程序不是并行的-您需要使用线程。 Please google it. 请用谷歌搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM