1
#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

3 Answers 3

8

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);
Sign up to request clarification or add additional context in comments.

3 Comments

You were faster. Remind me to upvote Your answer tomorrow as I don't have any votes left today.
@Dave - took care of that for you :)
@Nyan I recommend to use two-dimensional array rather than double indirect pointers - would have saved the OP form this trouble at all.
2

You are only mallocing 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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.