S
subirs
Hi,
I am trying to write a simple code in C using memory allocation. It
gives me segmentation fault. I have tried using mtrace. There are no
memory leaks and no segmentation fault unless I uncomment the line
for(i=0;i<=xcols;i++) x=0.0;
That is If I try to write to any of the dynamically allocated arrays
it gives me seg, fault. The code is attached , any helpis deeply
appreciated.
Regards
Subir
---------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<mcheck.h>
int main()
{
mtrace();
int trows=100;
int xcols=90;
int i,j,k;
double dx,dt,temp,temp1;
double **matu;
matu=malloc(trows* sizeof(*matu));
for(i=0; i<trows; i++)
{
matu=malloc(xcols * sizeof(*matu));
if ( matu == NULL)
{
printf("No space for allocation of ith=%d row",i);
exit(0);
}
}
double *x=malloc(xcols * sizeof(x));
double *t=malloc(trows * sizeof(t));
for(i=0;i<=xcols;i++) x=0.0;
//for(i=0;i<=trows;i++) t=0.0;
//for(i=0;i<=xcols;i++)
//for(j=0;j<=trows;j++)
//matu[j]=0.0;
/*dx=(1.0-0.0)/xcols;
dt=(1.0-0.0)/trows;
for(i=0;i<=xcols;i++)
x=x[0]+dx*i;
for(i=0;i<=trows;i++)
t=t[0]+i*dt; */
for(i=0; i<trows; i++)
free(matu);
free(matu);
free(x);
free(t);
muntrace();
return 0;
}
I am trying to write a simple code in C using memory allocation. It
gives me segmentation fault. I have tried using mtrace. There are no
memory leaks and no segmentation fault unless I uncomment the line
for(i=0;i<=xcols;i++) x=0.0;
That is If I try to write to any of the dynamically allocated arrays
it gives me seg, fault. The code is attached , any helpis deeply
appreciated.
Regards
Subir
---------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<mcheck.h>
int main()
{
mtrace();
int trows=100;
int xcols=90;
int i,j,k;
double dx,dt,temp,temp1;
double **matu;
matu=malloc(trows* sizeof(*matu));
for(i=0; i<trows; i++)
{
matu=malloc(xcols * sizeof(*matu));
if ( matu == NULL)
{
printf("No space for allocation of ith=%d row",i);
exit(0);
}
}
double *x=malloc(xcols * sizeof(x));
double *t=malloc(trows * sizeof(t));
for(i=0;i<=xcols;i++) x=0.0;
//for(i=0;i<=trows;i++) t=0.0;
//for(i=0;i<=xcols;i++)
//for(j=0;j<=trows;j++)
//matu[j]=0.0;
/*dx=(1.0-0.0)/xcols;
dt=(1.0-0.0)/trows;
for(i=0;i<=xcols;i++)
x=x[0]+dx*i;
for(i=0;i<=trows;i++)
t=t[0]+i*dt; */
for(i=0; i<trows; i++)
free(matu);
free(matu);
free(x);
free(t);
muntrace();
return 0;
}