Program crashes when launched normally but doesn't in debug mode

Viewed 67

I've been working on a small program that was assigned at school.
The goal is to create a dynamic matrix with values from a file containing its dimensions followed by rows containing a value and its position in the matrix like this:

MatrixRows MatrixColumns    
ValueA RowA ColumnA  
ValueB RowB ColumnB  
...

(also, all the other elements need to be initialized to 0 through calloc)

which I have done like this

int **readFromFile(int *rows, int *columns) {
    FILE *fp;
    int **tmpMatrix, rowIndex, columnIndex, matValue;

    if ((fp = fopen(FILENAME, "r")) != NULL) {

        fscanf(fp, "%d %d", rows, columns);
        tmpMatrix = allocMatrix(*rows, *columns);

        while ( (fscanf(fp, "%d %d %d", &matValue, &rowIndex, &columnIndex) != EOF) ) {
            tmpMatrix[rowIndex][columnIndex] = matValue;
        }
        return tmpMatrix;
    }
}

It all seems to work fine, until I call the printMatrix function (described below). it starts printing, but crashes just before printing the last row unless I launch it in debug mode, where it works smooth.

void printMatrix(int **matrix, int rows, int columns) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
    return;
}

What am I missing? Isn't it just a normal print? Thanks in advance!

0 Answers
Related