Skip to content
Advertisement

c program works on windows take segmantation fault on linux

I wrote some c code on codeblocks. It works perfectly fine on Windows but gave segmantation fault on Linux. Why ?

This is main. I used 3 libraries and opencells method calls a recursive method.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int main(int argc , char *argv[])
{
     srand(time(NULL));
    int size=atoi(argv[1]),trial=atoi(argv[2]);      //! program basladıgında gelen argumanlar
    int i,j;                 //! dongu degişkenleri
        int **matrix = (int **)malloc(size * sizeof(int));          //!matriksin 1 boyutunu dinamik olarak yarattık
        int *counters = (int *)malloc(trial * sizeof(int));         //! buda counterları tutcagımız array

            for (i=0; i<size; i++)
                matrix[i] = (int *)malloc(size * sizeof(int)); //! 2. boyutada yarattık

         for(i=0;i<size;i++)
            for(j=0;j<size;j++)  //! matrixsi sıfırla saçma sapan degerler geliyo yoksa
                matrix[i][j]=0;

            for(i=0;i<trial;i++)
            {
                   counters[i]=opencells(matrix,size); //!Random kapı açan ve bunun sayısını donduren fonksyon
            }
            printboard(matrix,size,trial,counters); //!Output.txtye yazdır
            for (i=0; i<size; i++)
                free(matrix[i]);  //! ramden aldıgımız yerleri sal gitsin
            free(matrix);          //! bosu bosuna makinayı zorlamayalım
    return 0;
}

Advertisement

Answer

int **matrix = (int **)malloc(size * sizeof(int));

Change: (int) to (int*)

int **matrix = (int **)malloc(size * sizeof(int*));

Because sizeof(int) and sizeof(int*) maybe different, so your program maybe crashed when access the not allocated memory.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement