gpt4 book ai didi

c - 初始化 1 个以上的 int 会导致段错误(核心转储)错误

转载 作者:行者123 更新时间:2023-11-30 15:10:53 25 4
gpt4 key购买 nike

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

#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)
<小时/>

使用太多内存会导致这样的错误吗?

谢谢。-汤姆

最佳答案

问题出在这一行:

int fd[2*numchild][2];

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

关于c - 初始化 1 个以上的 int 会导致段错误(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35950169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com