我正在用valgrind来完成我的程序以寻找内存泄漏.这是一个我不知道该怎么做的.
==15634== 500 (224 direct, 276 indirect) bytes in 2 blocks are definitely lost in loss record 73 of 392 ==15634== at 0x4007070: realloc (vg_replace_malloc.c:429) ==15634== by 0x807D5C2: hash_set_column(HASH*, int, char const*) (Hash.cpp:243) ==15634== by 0x807BB15: LCD::PluginDiskstats::PluginDiskstats() (PluginDiskstats.cpp:102) ==15634== by 0x806E021: LCD::Evaluator::Evaluator() (Evaluator.cpp:27) ==15634== by 0x8066A87: LCD::LCDControl::LCDControl() (LCDControl.h:16) ==15634== by 0x80667F5: main (Main.cpp:8)
这是代码:
/* add an entry to the column header table */ void hash_set_column(HASH * Hash, const int number, const char *column) { if (Hash == NULL) return; Hash->nColumns++; Hash->Columns = (HASH_COLUMN *)realloc(Hash->Columns, Hash->nColumns * sizeof(HASH_COLUMN)); // line 243 Hash->Columns[Hash->nColumns - 1].key = strdup(column); Hash->Columns[Hash->nColumns - 1].val = number; qsort(Hash->Columns, Hash->nColumns, sizeof(HASH_COLUMN), hash_sort_column); }
我应该在内存管理方面做点什么吗?
问题是如果realloc()
失败,函数将返回NULL,但仍将分配原始块.但是,您刚刚覆盖了指向该块的指针,无法再释放(或使用)它.