Search code examples
carraysloopsabort

Abort trap 6 error in C


I have this code:

void drawInitialNim(int num1, int num2, int num3)
{
    int board[2][50]; //make an array with 3 columns
    int i; // i, j, k are loop counters
    int j;
    int k;

    for(i=0;i<num1+1;i++)      //fill the array with rocks, or 'O'
        board[0][i] = 'O';     //for example, if num1 is 5, fill the first row with 5 rocks
    for (i=0; i<num2+1; i++)
        board[1][i] = 'O';
    for (i=0; i<num3+1; i++)
        board[2][i] = 'O';

    for (j=0; j<2;j++) {       //print the array
      for (k=0; k<50;k++) {
         printf("%d",board[j][k]);
      }
    }
   return;
}

int main()
{
    int numRock1,numRock2,numRock3;
    numRock1 = 0;
    numRock2 = 0;
    numRock3 = 0; 
    printf("Welcome to Nim!\n");
    printf("Enter the number of rocks in each row: ");
    scanf("%d %d %d", &numRock1, &numRock2, &numRock3);
    drawInitialNim(numRock1, numRock2, numRock3); //call the function

    return 0;
}

When I compile this with gcc, it is fine. When I run the file, I get the abort trap 6 error after entering the values.

I have looked at other posts about this error, and they don't help me.


Solution

  • Try this:

    void drawInitialNim(int num1, int num2, int num3){
        int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 
    
        int i, j, k;
    
        for(i=0; i<num1; i++)
            board[0][i] = 'O';
        for(i=0; i<num2; i++)
            board[1][i] = 'O';
        for(i=0; i<num3; i++)
            board[2][i] = 'O';
    
        for (j=0; j<3;j++) {
            for (k=0; k<50; k++) {
                if(board[j][k] != 0)
                    printf("%c", board[j][k]);
            }
            printf("\n");
        }
    }