我正在努力制作康威的生活游戏,当我使用单线程时,它运行得很好但是如果我尝试使用clone()来制作它,则会导致分段错误。如果可能,任何人都可以帮我找出原因吗?
主要
int main(int argc, char *argv[])
{
const int STACK_SIZE=65536;
int checkInit=0;
int i;
int j;
int *stack;
int *stackTop;
FILE *file1;
int numThreads;
if(argc != 3) {
fprintf(stderr, "Usage: %s <Executable> <Input file> <Threads>\n", argv[0]);
exit(1);
}
file1=fopen(argv[1],"r");
if(file1==NULL) { //check to see if file exists
fprintf(stderr, "Cannot open %s\n", argv[1]);
exit(1);
}
fscanf(file1,"%d",&N);
stack=malloc(STACK_SIZE);
if(stack==NULL) {
perror("malloc");
exit(1);
}
stackTop=stack+STACK_SIZE;
numThreads=atoi(argv[2]);
calcPerThread=N/numThreads;
eCalcPerThread=calcPerThread;
B = malloc(N * sizeof(int *));
A = malloc(N * sizeof(int *));
for (i = 0; i < N; i++) {
A[i] = malloc(N * sizeof(int));
B[i] = malloc(N * sizeof(int));
}
system("clear");
for(i=0; i<N+2; i++)
printf("-");
printf("\n");
for (i=0; i<N; i++) {
printf("|");
for(j=0; j<N; j++) {
if(A[i][j] == 1)
printf("x");
else
printf(" ");
}
printf("|\n");
}
for(i=0; i<N+2; i++)
printf("-");
printf("\n");
printf("Press [ENTER] for the next generation.\n");
fclose(file1);
while(getchar()) {
system("clear");
clone(growDie,stackTop,CLONE_VM|CLONE_FILES,NULL);
display(N);
}
}
GDB错误
Program received signal SIGSEGV, Segmentation fault.
clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:72
72 ../sysdeps/unix/sysv/linux/i386/clone.S: No such file or directory.
in ../sysdeps/unix/sysv/linux/i386/clone.S
Current language: auto
The current source language is "auto; currently asm".
我认为问题来自stackTop,但我不确定。
答案 0 :(得分:2)
你的指针运算有问题。
stack=malloc(STACK_SIZE);
分配STACK_SIZE字节。但..
int *stack;
stackTop=stack+STACK_SIZE;
stack是指向int的指针。因此,指针运算将使每个+1为4个字节而不是1个字节(假设为32位系统)。
您可以通过多种方式解决此问题:
我更喜欢第一种选择。