'How to use turn variable to synchronize in C?

I am new to semaphore and I am trying to let my child process to execute the code one by one using the turn variable, which means that if it isnt the child's turn, it will have to wait for its turn (when turn increments). And I was supposed to print an output of

I am child 0
0 1 2 3 4 5 6 7 8 9
I am child 1
10 11 12 13 14 15 16 17 18 19
etc.

But when I run the code, it gave me a segmentation fault, core dumped error. Anyone can assist on this?

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/wait.h>

#define NUM_PROCESSES 5

int main() {
    int i, j, pid;
    int *turn;
    int sharedid;
    //create a share memory region
    sharedid = shmget(IPC_PRIVATE, 4*sizeof(int), IPC_CREAT | 0600);
   //attach turn to the shared memory region
    turn = (int *) shmat(sharedid, NULL,0);
   // initialize it to 0
    *turn = 0;
    
    
    for(i=0; i<NUM_PROCESSES; i++) {
        if((pid = fork()) == 0) {
        
            break;
    }   
    }
    
    if(pid != 0) {
       while (*turn != i); 
       printf("I am child %d\n", i);

        for(j = i*10; j<i*10 + 10; j++){
            printf("%d ", j);
            fflush(stdout);
            usleep(250000);
        }

        printf("\n\n");
        *turn = *turn + 1;
          
    }
    else {
        for(i=0; i<NUM_PROCESSES; i++){ 
            wait(NULL);
        }
    shmdt(turn);
    shmctl(sharedid, IPC_RMID, 0);
          
    }
}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source