gpt4 book ai didi

c - 内存资源(strdup)

转载 作者:行者123 更新时间:2023-11-30 20:41:05 25 4
gpt4 key购买 nike

我调用 strdup 来复制 set_device( devname ) 中的“card”字符串set_device( 设备名称 )然后我使用“card”打开混音器:

devname 的格式为 hw:0/Mic

static char *card, *channel;
static snd_mixer_t *handle = NULL;
static snd_mixer_elem_t *elem = NULL;
static long min, max, vol;

static void open_mixer( void )
{
int err;
static snd_mixer_selem_id_t *sid = NULL;
if ((err = snd_mixer_open (&handle, 0)) < 0) {
return;
}
if ((err = snd_mixer_attach (handle, card)) < 0) { /* memory leak */
goto error;
}
if ((err = snd_mixer_selem_register (handle, NULL, NULL)) < 0) {
goto error;
}
if ((err = snd_mixer_load (handle)) < 0) {
goto error;
}
snd_mixer_selem_id_malloc(&sid);
if (sid == NULL)
goto error;
snd_mixer_selem_id_set_name(sid, channel);
if (!(elem = snd_mixer_find_selem(handle, sid))) {
goto error;
}
if (!snd_mixer_selem_has_playback_volume(elem)) {
goto error;
}
snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
if ((max - min) <= 0) {
goto error;
}
snd_mixer_selem_id_free(sid);
return;

error:
if (sid)
snd_mixer_selem_id_free(sid);
if (handle) {
snd_mixer_close(handle);
handle = NULL;
}
return;
}

int set_device( const char *devname )
{
int i;

if (card) free(card);
card = strdup( devname );
if( !card ) return -1;

i = strcspn( card, "/" );
if( i == strlen( card ) ) {
channel = "Mic";
} else {
card[i] = 0;
channel = card + i + 1;
}
open_mixer();
if (!handle) {
fprintf( stderr, "mixer: Can't open mixer %s, volume unavailable.\n", card );
return -1;
}
return 0;
}

请帮助我防止调用 strdup 后内存泄漏

最佳答案

函数strdup使用malloc分配内存。如果您想避免由于 strdup 导致内存泄漏,您必须释放 strdup 的返回值(在您的情况下为变量 card)不再使用该数据。

这是 strdup 人的部分内容:

char *strdup(const char *s);

The strdup() function returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with malloc(3), and can be freed with free(3).

关于c - 内存资源(strdup),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18451593/

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