Reputation: 1385
#include<stdlib.h>
#include<stdio.h>
int main(){
int row;
int col;
int i=1;
double ** doubleNode;
// *(*(doubleNode+row)+coln)
doubleNode=malloc(sizeof(double)*4);
*doubleNode=malloc(sizeof(double *)*4);
for(row=0; row <4; row++){
for(col =0; col<4;col++){
*(*(doubleNode+row)+col)=i;
i++;
}
}
free(doubleNode);
free(*doubleNode);
return 0;
}
this is a test code for a double pointer. it compiles fine with gcc, but when i run it. it gives me segmetation fault. do u know where i did wrong?
thanks
Upvotes: 1
Views: 229
Reputation: 23774
You are only malloc
ing the first "column" of your matrix. This row:
*doubleNode=malloc(sizeof(double *)*4);
is equivalent with this:
doubleNode[0]=malloc(sizeof(double *)*4);
You need to do this once for every column (or row). Additionally, I think the types in your sizeof
statements should be reversed.
Upvotes: 2
Reputation: 170819
Memory for doubleNode
must be allocated as a pointers to double and then you should allocate memory for each pointer in array:
doubleNode=malloc(sizeof(double*)*4);
for (int i = 0; i < 4;++i)
doubleNode[i]=malloc(sizeof(double)*4);
The same applies to freeing the memory:
for (int i = 0; i < 4;++i)
free(doubleNode[i]);
free(doubleNode);
Upvotes: 8
Reputation: 6229
I can see one problem immediately. You free doubleNode, then dereference it. Swap the two free's around.
Also, I think your mallocs are the wrong size. The first should be sizeof(double *) and the second sizeof(double).
Edit: And as others have said, you've only allocated the first "column" in your matrix.
Upvotes: 1