tags:

views:

109

answers:

3
+1  Q: 

c malloc question

#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

+1  A: 

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.

developmentalinsanity
+8  A: 

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);
Vladimir
@Vladimir, You were faster. Remind me to upvote Your answer tomorrow as I don't have any votes left today.
Dave
I recommend this style:pointer = malloc(sizeof(*pointer));
Nyan
@Dave - took care of that for you :)
Tim Post
@Nyan I recommend to use two-dimensional array rather than double indirect pointers - would have saved the OP form this trouble at all.
Dave
+2  A: 

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.

You