动态数组:使用realloc()的无内存泄漏 [英] Dynamic arrays: using realloc() without memory leaks
本文介绍了动态数组:使用realloc()的无内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用的realloc来调整分配的内存:
I use realloc to resize the memory allocated:
char **get_channel_name(void)
{
char **result;
int n;
result = (char **) 0;
for (elem = snd_mixer_first_elem(handle), n = 0; elem; elem = snd_mixer_elem_next(elem)) {
if (!snd_mixer_selem_is_active(elem))
continue;
if (snd_mixer_selem_has_playback_volume(elem) &&
snd_mixer_selem_has_playback_switch(elem) &&
snd_mixer_selem_has_capture_switch(elem)) {
if (result == (char **) 0)
result = (char **) malloc(sizeof(char *));
else
result = (char **) realloc(result, sizeof(char *) * (n + 1)); /* nulled but not freed upon failure */
result[n++] = strdup(snd_mixer_selem_get_name(elem));
}
}
if (result == (char **) 0)
return NULL;
result = (char **) realloc(result, sizeof(char *) * (n + 1)); /* nulled but not freed upon failure */
result[n] = NULL;
return result;
}
当我检查code。与cppcheck工具静态C / C ++ code分析,打印以下warings:
When I check code with cppcheck tool static C/C++ code analysis, printed the following warings:
Common realloc mistake: 'result' nulled but not freed upon failure
我
如何解决这两个可能的内存泄漏?
How can I fix these 2 possible memory leaks?
推荐答案
如果的realloc()
失败则返回 NULL
。
所以,如果你这样做(并假设的realloc()
将失败)
So if you do (and assuming realloc()
would fail)
result = realloc(result, ...);
结果
将被赋予 NULL
和它所指向的不是免费()
ED和地址为免费()
ED是丢失。
result
will be assigned NULL
and what it pointed to is not free()
ed and the address to be free()
ed is lost.
要解决这个问题吗:
void * tmp = realloc(result, ...);
if (NULL == tmp)
{
/* Handle error case, propably freeing what result is pointing to. */
}
else
{
result = tmp;
}
这篇关于动态数组:使用realloc()的无内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文