【问题标题】:free() char with assigned value before call strdup()在调用 strdup() 之前分配值的 free() char
【发布时间】:2013-07-29 17:06:14
【问题描述】:

我想用“/dev/mixer:line”或“/dev/mixer:cd”这个表格从gtk_entry设置混音器设备。

用户必须进入此格式的混音器设备设置:

/dev/mixer:line

or:

/dev/mixer:cd

为此,我编写代码来设置混音器,并且与 strdup() 函数有同样的困境。 在调用 strdup() 之前 free() char 分配值是错误的吗?

char *mixer_device = "/dev/mixer";
int mixer_channel = SOUND_MIXER_LINE;
int fd = -1;

int get_volume( void )
{
    int v, cmd, devs;
    int curvol = 0;

    if( fd < 0 ) fd = open( mixer_device, O_RDONLY );
    if( fd != -1 ) {

            ioctl( fd, SOUND_MIXER_READ_DEVMASK, &devs );
            if( devs & mixer_dev_mask ) {
                    cmd = MIXER_READ( mixer_channel );
            } else {
                    return curvol;
            }

            ioctl( fd, cmd, &v );
            curvol = ( v & 0xFF00 ) >> 8;
    }

    return curvol;
}

char *core_devnames[] = SOUND_DEVICE_NAMES;

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

    /* if (mixer_device) free (mixer_device) <-- It is wrong ??? */ 
    mixer_device = strdup( devname );
    if( !mixer_device ) return -1;

    i = strcspn( mixer_device, ":" );
    if( i == strlen( mixer_device ) ) {
            channame = "line";
    } else {
            mixer_device[ i ] = 0;
            channame = mixer_device + i + 1;
    }
    fd = open( mixer_device, O_RDONLY );
    if( fd == 0 ) {
            fprintf( stderr, "mixer: Can't open device %s, "
                     "mixer volume and mute unavailable.\n", mixer_device );
            return -1;
    }

    return 0;
}

在调用strdup()之前free()char是错误的

【问题讨论】:

  • 在非动态分配的内存上调用 free 是未定义的行为。您在此处将初始值设置为字符串文字:char *mixer_device = "/dev/mixer";

标签: c free strdup


【解决方案1】:

如果指针指向使用malloc() 分配的内存,您只能调用free()。在您的程序中,mixer_device 最初指向一个文字字符串,因此调用 free() 会导致未定义的行为。

您需要另一个变量来跟踪它是指向初始文字字符串还是使用strdup() 创建的新字符串,而不是检查mixer_device 是否为空。或者,您的启动代码可以这样做:

mixer_string = strdup("/dev/mixer");

所以释放它总是安全的。

【讨论】:

    【解决方案2】:

    你在这里设置初始值:

    char *mixer_device = "/dev/mixer";
    

    它现在指向一个字符串文字,所以如果你尝试在mixer_device 上调用free,你将拥有undefined behaviorfree 只能在动态分配的内存上调用,即从malloc,@ 987654328@ 等...一种解决方案是使用strdup 来初始化您的变量:

    mixer_device = strdup("/dev/mixer") ;
    

    【讨论】:

      【解决方案3】:

      用 NULL 初始化;

      char *mixer_device = NULL;
      

      mixer_device 的值为NULL 或者当然是通过malloc(), strdup(), realloc() 分配的值时,可以使用free(mixer_device)。当 null 时,没有任何东西被释放,也没有 UB。然后,当您想分配 mixer_device 时,只需

      free(mixer_device);
      mixer_device = strdup(NewName);
      

      在最后main(),执行一个final

      free(mixer_device);
      

      【讨论】:

        猜你喜欢
        • 2011-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-02
        • 1970-01-01
        • 2021-12-29
        • 2013-09-09
        • 1970-01-01
        相关资源
        最近更新 更多