c - 尝试克隆函数时出现段错误(在 C 中)

标签 c linux segmentation-fault clone

我正在尝试制作康威的生命游戏,当我将其设置为单线程时,它工作得很好,但如果我尝试使用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 上,但我不太确定。

最佳答案

你的指针算术有问题。

stack=malloc(STACK_SIZE);

分配 STACK_SIZE 字节。但是..

int *stack;
stackTop=stack+STACK_SIZE;

stack 是一个指向 int 的指针。因此,指针算术将导致每个 +1 为 4 个字节而不是 1 个字节(假设是 32 位系统)。

您可以通过多种方式解决此问题:

  • 使 stack 和 stackTop 使用“char *”而不是“int *”
  • 在算术中转换堆栈:stackTop = ((unsigned int)stack)+STACK_SIZE。

我更喜欢第一个选项。

关于c - 尝试克隆函数时出现段错误(在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28597698/

相关文章:

linux - 在 x86 中将字符串定义为字节 (db) 和将字符串定义为字/双字 (dw/dd) 有什么区别

c - 查看代码以读取外部 adc 值

c - 具有动态矩阵的动态结构

C++:将 LPTSTR 转换为字符数组

linux - $#、$1 和 $2 是什么意思?

c - select() 似乎会出现段错误/终止

c - C 中元音变音 'A' 的用途或等效项是什么?

mySQL root 密码无效

c - 在 C 中的字符串反转期间释放指针时出现段错误

c - fopen/fclose 上的段错误