【问题标题】:Memory resource ( strdup )内存资源 ( strdup )
【发布时间】:2013-08-29 09:12:12
【问题描述】:

我调用 strdup 来复制 set_device(devname) 中的“card”字符串 设置设备(开发名称) 然后我用'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 后的内存泄漏

【问题讨论】:

  • 避免内存泄漏的关键是在完成后释放分配的内存...
  • 静态字符 *card=NULL, *channel=NULL;您不能将“麦克风”分配给通道,因为它没有与之关联的任何内存,只是一个指针。使用 char *channel[10] = {}; 可能会更好

标签: c memory-leaks alsa strdup


【解决方案1】:

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

这是 strdup 人的部分陈述:

char *strdup(const char *s);

strdup() 函数返回一个指向新字符串的指针,该字符串是字符串 s 的副本。使用 malloc(3) 获得新字符串的内存,并且可以 用 free(3) 释放。

【讨论】:

    猜你喜欢
    • 2014-09-20
    • 2016-01-18
    • 2016-06-04
    • 2012-08-14
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    相关资源
    最近更新 更多