You are not logged in.
Hallo everyone.
I was experimenting with a toy code and I got some strange segmentation faults. In particular, I am trying to dynamically allocate a 2D array which is a contiguous in memory. I try to do it by declaring
double **A;
and then allocate space for n pointers to the array's n lines :
A=(double**)malloc(n);
finally I allocate my array:
A[0]=(double *)malloc((n*n)*sizeof(double));
and finally I assign each of my line pointers to the appropriate matrix line :
for(i=1;i<n;i++) {
A[i]=A[0]+i*n;
}
I check that everything is ok by manually looking at the addresses. The problem is that if I run it for n>4 it sefaults . As far as I know, it should run.
Are there any ideas ?
This is the complete code I compile:
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int i,j,n=5;
double **A;
A=(double**)malloc(n);
A[0]=(double *)malloc((n*n)*sizeof(double));
printf("A[%d]=%d\n",0,&A[0]);
for(i=1;i<n;i++) {
A[i]=A[0]+i*n;
printf("A[%d]=%d\n",i,&A[i]);
}
for(i=0;i<n;i++) {
for(j=0;j<n;j++)
printf(" %d,%d:%d\t",i,j,&(A[i][j]));
printf("\n");
}
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
A[i][j]=i*n+j;
printf("\t A(%d,%d)=%f- %d",i,j,A[i][j],&A[i][j]);
}
printf("\n");
}
free(A[0]);free(A);
return 0;
}
Offline
A=(double**)malloc(n);
This is probably not what you want since malloc will reserve
a total of n bytes in your code. Presumably, you want n * sizeof(*double)
bytes since A is an array of pointers to double.
Offline
You are absolutely correct! well, almost, it should be
sizeof(double*)
. Thank you very much! Silly me, I should have seen it.
Offline
nspattak: this might interest: http://www.wolfbane.com/fortran/append-c.html
Offline
It is. Thank you very much.
To be honest, when writting scientific codes i do not use dynamically created vectors/arrays. I was trying to do it mostly to improve my understanding of the language and because I saw it as a challenge.
Thanks to both of you.
Offline
To be honest, when writting scientific codes i do not use dynamically created vectors/arrays.
Because we all know how static, scientific data is.
Offline