使用sd-device枚举设备导致seg错误

问题描述 投票:0回答:1

#include <stdio.h>
#include <stdlib.h>
#include <systemd/sd-device.h>
int main() {
    sd_device *device;
    sd_device_enumerator *enumerator =NULL;
    const char **subsystem =NULL;
    // *subsystem = malloc(sizeof(char *));
    *subsystem = malloc(500);
    if (subsystem == NULL)
        printf("ohh");
    // Create a device enumerator
    int r = sd_device_enumerator_new(&enumerator);
    if (r< 0)
        printf("unable to create instance");
        printf("%d\n",r);
    //sd_device_enumerator_scan(enumerator);
    for (device = sd_device_enumerator_get_device_first(enumerator); device != NULL;
         device = sd_device_enumerator_get_device_next(enumerator)) {
        
            r = sd_device_get_subsystem(device, subsystem);
            if (r < 0) 
            printf("error in subsystem");
                
                printf(" %s\n", subsystem);
                if (subsystem != NULL) 
                free((char *)subsystem); // free the previous subsystem name
                            
            
}
}

编译上面的代码会导致段错误

gcc -o dev_enum test2.c -lsystemd 用于编译 请帮忙

c pointers udev
1个回答
0
投票

原因是空指针取消引用,这会调用未定义的行为:

const char **subsystem =NULL;
// *subsystem = malloc(sizeof(char *));
*subsystem = malloc(500);

在第 3 行中,

subsystem
被取消引用,这是一个空指针。

根据sd_device_get_sybsystem()

手册页
,第二个参数需要是
char **
,因此您只需将
subsystem
定义为
char *
,并将
&subsystem
作为第二个参数传递给
sd_device_get_subsystem()
.

其他一些问题:

  • malloc()
    和系列在失败时返回空指针。如果不检查它,就有可能通过后续的空指针取消引用来调用未定义的行为。打印
    "ooh"
    并不能解决问题。

  • free()
    需要一个通用的
    void *
    ,它可以隐式地与任何其他指针类型相互转换。无需将其参数转换为
    char *

© www.soinside.com 2019 - 2024. All rights reserved.