初始化1个int导致分段错误(核心转储)错误

时间:2016-03-11 21:22:54

标签: c segmentation-fault runtime-error coredump

我使用此代码通过管道传输到子进程来读取文件:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
int numchild;
int i, j, len, fpos=0, val, count=0, total=0, alltotal=0;
pid_t pid;
int nums = 1000;
FILE * file;

printf("How many children to use: ");
scanf("%d", &numchild);
printf("\nWill use %d child process(es).\n", numchild);

int fd[2*numchild][2]; //parent+child pipe

// create all pipes
for (i=0; i<2*numchild; i++)
{
    pipe(fd[i]);
}

for (i=0; i<numchild; i++)
{
    if((pid = fork()) == 0) // child process
    {
        pid = getpid();

        // read from parent
        len = read(fd[i][0], &fpos, sizeof(fpos));
        if (len > 0)
        {
            file = fopen("file1.dat", "r");
            fseek (file, fpos, SEEK_SET);
            count = 0;
            total = 0;

            printf("Child(%d): Recieved position: %d\n", pid, fpos);

            // read from file starting at fpos
            // add values read to a total value
            while (count < (nums/numchild))
            {
                fscanf(file, "%i", &val);
                total += val;
                count++;
            }
            //write to parent
            write(fd[i+numchild][1], &total, sizeof(total));
            printf("Child(%d): Sent %d to parent.\n", pid, total);
        }
        else
        {
            printf("Child(%d): Error with len\n", pid);
        }

        _exit;
    }

    // parent process
    pid = getpid();

    fpos = ((i*nums*5)/numchild); // 5 is the offset of the file values

    // write to child process
    printf("Parent(%d): Sending file position to child\n", pid);
    write(fd[i][1], &fpos, sizeof(fpos));

    // wait for child responce
    len = read(fd[i+numchild][0], &total, sizeof(total));
    if (len > 0)
    {
        printf("Parent(%d): Recieved %d from child.\n", pid, total);
        alltotal += total;
        printf("Parent(%d): Total: %d\n", pid, alltotal);
    }
    else
    {
        printf("Parent(%d): Error with len\n", pid);
    }
}
}

我发现由于在代码顶部初始化alltotal=0而导致分段错误。上一次编辑迭代允许代码执行;现在添加alltotal后,它无效。

修改

我做了一些调试,虽然我不确定这对我意味着什么

Reading symbols from a.out...done.
(gdb) run
Starting program: /home/tames/Desktop/project1_data/a.out

Program received signal SIGBUS, Bus error.
0x0000000000400894 in main (argc=1, argv=0x7fffffffe998) at finalSum.c:14
14              printf("How many children to use: ");
(gdb) backtrace
#0  0x0000000000400894 in main (argc=1, argv=0x7fffffffe998) at finalSum.c:14
(gdb) frame 0
#0  0x0000000000400894 in main (argc=1, argv=0x7fffffffe998) at finalSum.c:14
14              printf("How many children to use: ");
(gdb)

耗尽太多内存会导致这样的错误吗?

谢谢。 - 汤姆

1 个答案:

答案 0 :(得分:1)

问题出在这一行:

int fd[2*numchild][2];

执行此声明时,numchild包含垃圾值。在创建数组之前,需要初始化numchild。将该行移至scanf

之后