Search code examples
csegmentation-faultmultidimensional-arrayrealloc

I get segmentation fault when I try to insert new row into 2D-Array using realloc


When ever the program finds a row in witch the first element's last number and the last element's last number divide by 2, then it should add other row to the matrix. I need to do this using dynamic allocation. Here is the code:

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

int **a;
int cifra(int n){

    int c=0;
    while (n)
    {
        c=n%10;
        n/=10;`
    }
    return c;
 }

 int conditie(int i, int m)
 {
     if(cifra(a[i][0])%2==0 && a[i][m-1]%2==0)
        return 1;
    return 0;`
 }

 int main()
 {
    int i,j,n,m,k,l;
    printf("n=");
    scanf("%d",&n);
    printf("m=");
    scanf("%d",&m);`

    a=(int**)malloc(n*sizeof(int*));
    a[0]=(int*)malloc(n*m*sizeof(int));

    for( i=1;i<n;i++)
        a[i]=a[i-1]+m;

    for(i=0;i<n;i++)
        for(j=0;j<m;j++)
            {
                printf("a[%d][%d]=",i,j);
                scanf("%d",&a[i][j]);
            }
    for(i=0;i<n;i++)
        if(conditie(i,m))
        {
           n++;
           a=(int**)realloc(a,n*sizeof(int*));
           for(k=n-1;k>i;k--)
               for (l=0;l<m;l++)
                    a[k][l] = a[k-1][l]; //the program seems to be crashing here
            for(j=0;j<m;j++)
                a[i+1][j]=-1;
        }
    for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
                {
                    printf("%d",a[i][j]);
                }
            printf("\n");
        }
    free(a[0]);
    free(a);
    return 0;
    }

Solution

  • This is your problem.

    for( i=1;i<n;i++)
        a[i]=a[i-1]+m;
    

    You're assigning arbitrary pointers to the a[i]'s and when you deference them it throws a segmentation fault.