开发者

How to init and malloc array to pointer on C

It looks like I have a memory leak when I try to initializ an array of pointers. This my code:

void initLabelTable(){
    register int i;
    hashNode** hp;
    labelHashTable = (hashNode**) malloc(HASHSIZE*sizeof(hashNode*));
    hp = labelHashTable;
    for(i=0; i<HASHSIZE; i++) {
        *(hp+i) = NULL;
    }
}

Update:

I have this code:

c = fgetc(fp);

printf("%c",c);
line[MAXIMUM_LIN开发者_如何转开发E_LENGTH] = '\0';

initLabelTable();
c = fgetc(fp);

I get a segmentation fault on last row although the first getc succeeds. When I watch fp I see a different address. Any ideas?


No, this function by itself doesn't leak any memory. It allocates memory for labelHashTable, which, according to it's name, is what it's supposed to do.

Make sure that the memory pointed to by labelHashTable is freed once you're finished using it, else you will have a memory leak there. Also don't call initLabelTable() repeatedly without freeing labelHashTable before each subsequent call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜