以下函数会泄漏内存,有什么想法吗?
map.c:
#define INITIAL_SIZE 10
#define KEYS_AND_VALUES 0
struct Map_t {
char **keys;
char **values;
int size;
int max_size;
int iterator;
};
Map mapCreate()
{
Map map = malloc(sizeof(*map));
if (!map)
{
return NULL;
}
map->keys = malloc(INITIAL_SIZE * sizeof(char *));
if (!map->keys)
{
free(map);
return NULL;
}
map->values = malloc(INITIAL_SIZE * sizeof(char *));
if (!map->values)
{
free(map->keys);
free(map);
return NULL;
}
map->size = 0;
map->max_size = INITIAL_SIZE;
initializeElements(map,0,map->max_size,KEYS_AND_VALUES);
return map;
}
static void initializeElements(Map map, int initial_index, int last_index, int mode)
{
for (int i=initial_index;i<last_index;i++)
{
if (mode==KEYS || mode==KEYS_AND_VALUES)
{
map->keys[i]=NULL;
}
if (mode==VALUES || mode==KEYS_AND_VALUES)
{
map->values[i]=NULL;
}
}
}
void mapDestroy(Map map)
{
if (!map)
{
return;
}
mapClear(map);
free(map->keys);
free(map->values);
free(map);
}
map.h:
typedef struct Map_t* Map;
valgrind报告:
==1817== in use at exit: 524 bytes in 26 blocks
==1817== total heap usage: 30,132 allocs, 30,106 frees, 575,911 bytes allocated
==1817==
==1817== 262 (32 direct, 230 indirect) bytes in 1 blocks are definitely lost in loss record 17 of 18
==1817== at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==1817== by 0x402AAF: mapCreate (map.c:106)
==1817== by 0x402420: testMapForEach (main.c:272)
==1817== by 0x4028A2: main (main.c:324)
I am sure that the function in handled well in testMapForEach()
and main
Note: I'm mostly that The leak mostly (99.9%) occurs when one of the uses of malloc fails.
The test if needed at all consists of 300 lines of code at: https://github.com/gur111/MtmEx1Tester/blob/master/map_tests.c
That's why I ask you to focus on mapCreate().
Thanks
更新: 确认后,testMapForEach(在测试代码上可用)捕获到泄漏