gpt4 book ai didi

c - 动态数组 : using realloc() without memory leaks

转载 作者:太空狗 更新时间:2023-10-29 14:53:16 24 4
gpt4 key购买 nike

我使用 realloc 来调整分配的内存大小:

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;
}

当我使用cppcheck工具静态C/C++代码分析检查代码时,打印了以下警告:

Common realloc mistake: 'result' nulled but not freed upon failure

如何修复这 2 种可能的内存泄漏?

最佳答案

如果 realloc() 失败,则返回 NULL

所以如果你这样做(假设 realloc() 会失败)

result = realloc(result, ...);

result 将被分配为 NULL 并且它指向的内容不是 free() 并且地址是 free( )ed 丢失了。

要解决此问题,请执行以下操作:

{
void * tmp = realloc(result, ...);
if (NULL == tmp)
{
/* Handle error case, propably freeing what result is pointing to. */
}
else
{
result = tmp;
}
}

关于c - 动态数组 : using realloc() without memory leaks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27589846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com