Search code examples
cmatrixrealloc

Reallocating a matrix' row count to a number larger than the initial value


I have a program to create a matrix with initial values and then changing the matrix to given values. But when I try to change the row count to a number equal to or larger than the initial value, the program crashes. What am I doing wrong here?

void fill(int row, int column, int **arr){
    int k = 0;
    for(int i = 0; i < row; i++){
       for(int j = 0; j < column; j++){
        *(*(arr + i)+j) = k;
           k++;}}}

void print(int row, int column, int **arr){
    for(int i = 0; i < row; i++){
       for(int j = 0; j < column; j++){
           printf("%d\t", *(*(arr +i ) + j));}
       printf("\n");}}

int **create(int row, int column){
    int **arr = (int **)malloc(row * sizeof(int *));
    for (int i=0; i<row; i++){
       *(arr + i) = (int *)malloc(column * sizeof(int));}
    return arr;}

int** modify(int oldRowCount, int row, int column, int **arr){
     arr =(int **) realloc(arr,(unsigned long) row * sizeof (int **));

     for(int i = 0; i < row; i++)
         *(arr + i) =(int *) realloc(*(arr+i),(unsigned long) column * sizeof (int));

     if(oldRowCount <= row){
         for (int i = oldRowCount; i < row; i++)
             *(arr + i) = (int *)malloc(column * sizeof(int));
     }
    else{
         for(int i = row + 1; i <= oldRowCount; i++)
             free(*(arr + i));
     }
     return arr;}

int main()
{
    int row = 4;
    int column = 4;
    int oldRowCount=row;

    int **arr = create(row,column);
    fill(row, column, arr);
    print(row, column, arr);

    while(1){
    oldRowCount = row;
    scanf("%d",&row);
    scanf("%d",&column);
    arr = modify(oldRowCount, row, column, arr);
    fill(row, column, arr);
    print(row, column, arr);
}
    return 0;
}

Solution

  • Its going on because realloc() try realloc empty memory. For example if new rows count = 6, then when i = 4, realloc try realloc pointer to nowhere. Also arr should be accepted by reference in this case.

    void modify(int row, int column, int oldRowCount, int** &arr) {
    arr = (int **)realloc(arr, row * sizeof(int*));
    for (int i = 0; i < oldRowCount; i++) {
        *(arr + i) = (int *)realloc(*(arr + i), column * sizeof(int));
    }
    
    for (int i = oldRowCount; i < row; i++) {
        *(arr + i) = (int *)malloc(column * sizeof(int));
    }
    
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < column; j++) {
            *(*(arr + i) + j) = 0;
    
        }
    }
    

    }