Search code examples
clinuxsegmentation-faultclone

Segmentation fault when trying to clone a function (in C)


i'm trying to make conway's game of life and when I have it single threaded, it works perfectly but if I try to use clone() to make it, it causes a segmentation error. If possible, can anyone help me figure out why?

Main

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 Error

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".

I THINK the problem is from stackTop, but i'm not exactly sure.


Solution

  • You have a problem in your pointer arithmetic.

    stack=malloc(STACK_SIZE);
    

    That allocates STACK_SIZE bytes. But..

    int *stack;
    stackTop=stack+STACK_SIZE;
    

    stack is a pointer to an int. Hence pointer arithmetic will cause each +1 to be 4 bytes not 1 byte (assuming a 32 bit system).

    You can fix this in a number of ways:

    • make stack and stackTop "char *" instead of "int *"
    • cast stack in the arithmetic: stackTop = ((unsigned int)stack)+STACK_SIZE.

    I prefer the first option.