此功能如何泄漏内存? (注意:我确定泄漏是使用自动检查器从内部进行的-我没有导致内存泄漏的特定值)
/**
* copyString: Returns a copy of target string
* @param source_str - Target string
* @return
* A pointer to the copied data
*/
char* copyString(const char *source_str)
{
if (!source_str)
{
return NULL;
}
char *copied_str = malloc(strlen(source_str) + 1);
if (copied_str == NULL)
{
return NULL;
}
return strcpy(copied_str, source_str);
}
valgrind报告:
==22237== 222 bytes in 3 blocks are possibly lost in loss record 2 of 4
==22237== at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==22237== by 0x401EB1: copyString (utilities.c:12)
==22237== by 0x4019E9: mapCopy (map.c:168)
==22237== by 0x401147: runMapCopyTest (main.c:171)
==22237== by 0x400F8A: runMapRandomTest (main.c:124)
==22237== by 0x400C8B: main (main.c:74)
根据要求,这是mapCopy的代码:
map.c:
struct Map_t {
char **keys;
char **values;
int size;
int max_size;
int iterator;
};
Map mapCopy(Map map)
{
if (!map)
{
return NULL;
}
Map dest = mapCreate();
if (!dest)
{
return NULL;
}
for (int i = 0; i < map->size; i++)
{
char* new_key=copyString(map->keys[i]);
char* new_value=copyString(map->values[i]);
MapResult result = mapPut(dest, new_key, new_value);
if (result!=MAP_SUCCESS)
{
free(new_key);
free(new_value);
mapDestroy(dest);
return NULL;
}
}
dest->iterator = map->iterator;
return dest;
}
mapCopy使用mapPut(我99%确信它根本不会泄漏内存):
MapResult mapPut(Map map, const char *key, const char *data)
{
if (!map || !key || !data)
{
return MAP_NULL_ARGUMENT;
}
char *dest = copyString(data);
if (!dest)
{
return MAP_OUT_OF_MEMORY;
}
int index=getIndexOfKey(map,key);
if (index!=ELEMENT_NOT_FOUND)
{
free(map->values[index]);
map->values[index]=dest;
}
else
{
char *copied_key = copyString(key);
if (!copied_key)
{
free(dest);
return MAP_OUT_OF_MEMORY;
}
if (map->size == map->max_size && expandMap(map) == MAP_OUT_OF_MEMORY)
{
free(copied_key);
free(dest);
return MAP_OUT_OF_MEMORY;
}
map->keys[map->size] = copied_key;
map->values[map->size] = dest;
map->size++;
}
return MAP_SUCCESS;
}
编辑:mapCopy肯定会泄漏内存。
她是我的代码,valgrind告诉它泄漏内存:
int main(){
printf("Running all tests, please be patient.\n");
Map test1=mapCreate();
mapPut(test1,"09","s");
mapPut(test1,"2","q");
Map copied=mapCopy(test1);
mapDestroy(test1);
mapDestroy(copied);
return 0;
}
如果调用copyString()
的函数在使用完之后忘记了在返回的指针上调用free()
,则可能会发生内存泄漏。
valgrind报告泄漏的内存缓冲区的分配位置,这通常与导致内存泄漏的错误的位置不同。我建议检查所有调用此函数的代码,以确保它适当地调用了free()
。