You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sd-device枚举设备出现段错误,请求技术协助

段错误问题排查与修复

问题根源分析

代码中存在多个导致段错误和逻辑错误的问题:

  • 空指针解引用:subsystem被初始化为NULL,直接执行*subsystem = malloc(500);会解引用空指针,触发段错误。
  • API使用错误:sd_device_get_subsystem的第二个参数是输出参数,库会自动将指向子系统名称的指针写入传入地址,不需要手动malloc内存,也不能调用free释放返回的字符串(内存由systemd库管理)。
  • 缺少设备扫描步骤:创建枚举器后未调用sd_device_enumerator_scan(enumerator),无法枚举到任何设备。
  • 逻辑缩进错误:多个if语句未加花括号,导致后续代码不受条件约束,执行逻辑混乱。
  • 错误的内存释放:尝试free((char *)subsystem),但subsystem本身未被malloc分配,且库返回的字符串不能手动释放。

修复后的代码

#include <stdio.h>
#include <stdlib.h>
#include <systemd/sd-device.h>

int main() {
    sd_device *device = NULL;
    sd_device_enumerator *enumerator = NULL;
    const char *subsystem = NULL;

    // 创建设备枚举器
    int r = sd_device_enumerator_new(&enumerator);
    if (r < 0) {
        printf("无法创建枚举器实例,错误码:%d\n", r);
        return EXIT_FAILURE;
    }

    // 扫描系统设备
    r = sd_device_enumerator_scan(enumerator);
    if (r < 0) {
        printf("扫描设备失败,错误码:%d\n", r);
        sd_device_enumerator_unref(enumerator);
        return EXIT_FAILURE;
    }

    // 遍历枚举到的设备
    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("获取子系统名称失败,错误码:%d\n", r);
            continue;
        }

        printf("设备子系统:%s\n", subsystem);
    }

    // 释放枚举器资源
    sd_device_enumerator_unref(enumerator);
    return EXIT_SUCCESS;
}

关键修复点说明

  1. 调整subsystem为一级指针,调用sd_device_get_subsystem时传入其地址,遵循API规范获取子系统名称。
  2. 添加sd_device_enumerator_scan调用,确保枚举器能加载系统设备列表。
  3. 修复所有条件判断的花括号,明确代码执行逻辑边界。
  4. 移除错误的malloc和free操作,交由systemd库管理相关内存。
  5. 添加资源释放和完善的错误处理,避免内存泄漏。

内容的提问来源于stack exchange,提问作者incompetent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:25:24