Search code examples
cmatrixrealloc

Dynamic reallocation of a square matrix


i'm tryng to create a function which adds dynamically 1 row and 1 column to a square matrix everytime i need. I'm posting the code as an example, there i start with a "1x1 matrix" of integers and i try to add a row and a column 5 times to obtain a fianl 5x5 matrix, i don't understand why the OS stops immediately the execution. In the for cycle first i reallocate the "column" array of pointers adding a new one (so a new row) then for each block of it (so for each row) i reallocate others N blocks of memory. It seems that i try to access to a forbidden address of memory but i don't understand why, what's wrong? P.S: my ennglis could not be perfect so if you don't understand what i'm trying to say i will explaind better.

 #include <stdlib.h>
 #include <malloc.h>
 #include <stdbool.h>
 #include <stdio.h>


int **M,N;

int main(int argc, char** argv) {

 N = 1;
 M = (int**)malloc(sizeof(int*));
 M[0] = (int*)malloc(sizeof(int));

 for (int i = 0; i < 5; i++) {
     N++;
     M = (int**)realloc(M, N * sizeof(int*));
     for (int k=0; k<N; k++)
     M[k] = (int*)realloc(M[k], N * sizeof(int));
  }
}

Solution

  • When you use realloc to expand an array, the new expanded elements in the array are not initialized. So when you realloc M, the additional pointers to memory are undefined, not NULL, so you cannot reference the expanded elements of M[] in the second realloc, until you initialize them to NULL.

     #include <stdlib.h>
     #include <malloc.h>
     #include <stdbool.h>
     #include <stdio.h>
    
    
    int **M,N;
    
    int main(int argc, char** argv) {
    
     N = 1;
     M = (int**)malloc(sizeof(int*));
     M[0] = (int*)malloc(sizeof(int));
    
     for (int i = 0; i < 5; i++) {
         N++;
         M = (int**)realloc(M, N * sizeof(int*));
    
          // Ensure the last M[] is NULL
         M[N-1] = NULL;
    
         for (int k=0; k<N; k++) 
             M[k] = (int*)realloc(M[k], N * sizeof(int));
      }
    }