简体   繁体   中英

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

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);

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM