Hi !
I recently switched to linux and started compiling my c programs on linux, I am using red hat 9.0 which has a gcc compiler. These are very simple programs that i tried to compile, htey compile fine but on running them I get a segmentation fault, which I don't really understand why. I read up on segmentation faults and it said it was due memory allocation error. I don't understand how, since these programs work fine in windows ????
The programs are:
program 1 : This prints a pascal triangle
program 2: Selection sort ( works 3 and smaller size arrays and segmentation fault at bigger arrays)Code:#include<stdio.h> #include<stdlib.h> int main() { int **pastriang, row=10, column=10, i, j; pastriang = (int**) malloc(row); for(i=0; i<row; i++) pastriang[i] = (int*) malloc(column); for(i=0; i<row; i++) for(j=0; j<column; j++) pastriang[i][j] = 0; for(i=0; i<row; i++) { for(j=0; j<column; j++) { if((i==j) || (j==0) ) pastriang[i][j] = 1; else if(j>i) pastriang[i][j] = 0; else pastriang[i][j] = pastriang[i-1][j-1] + pastriang[i-1][j]; } } for(i=0; i<row; i++) { for(j=0; j<column, j<=i; j++) printf("%3d", pastriang[i][j]); printf("\n"); } return 0; }
Code:#include<stdio.h> #include<stdlib.h> int main() { int *A, d, i, j; printf("enter the number of elements in the array\n"); scanf("%d", &d); A = (int*) malloc(d); for(i=0; i<d; i++) scanf("%d", &A[i]); int size= d; // -------------------------------- SELECTION SORT ------------------------------------------------// for(i=0; i<d; i++) { int position =0; int temp1 = A[0]; int temp2 =0; for(j=0; j<size; j++) { if(j == 0) continue; else { if(A[j]> temp1) { position =j; temp1 = A[j]; } } } temp2 = A[size-1]; A[size-1] = temp1; A[position] = temp2; size = size-1; } for(i=0; i<d; i++) printf("%d ", A[i]); return 0; }



LinkBack URL
About LinkBacks


