I have a simple initialization-population routine in C, that works fine in Linux. However when I try to run it in Code::Blocks, it produces a segmentation fault.
The code is below:
#include <stdio.h>
#include <stdlib.h>
double **rho, **ux, **uy;
double** allocate_double_array(int nx, int ny)
{
int i;
double** array=(double**) malloc( (nx * sizeof(double*)) + (nx*ny * sizeof(double**)) );
if (array==NULL) printf("Memory allocation failed!\n");
for(i=0; i<nx; ++i)
{
array[i] = (double*)(array + nx) + i * ny;
}
return array;
}
int main()
{
int nx = 100;
int ny = 100;
int x,y;
rho = allocate_double_array(nx,ny);
ux = allocate_double_array(nx,ny);
uy = allocate_double_array(nx,ny);
printf("Memory allocated_alter\n");
for (x=0; x<nx; x++)
{
for (y=0; y<ny; y++)
{
rho[x][y] = 1.0;
ux[x][y] = 2.0;
uy[x][y] = 3.0;
}
}
printf("Initialization Complete\n");
return 0;
}
Any idea where I am going wrong?