代码之家  ›  专栏  ›  技术社区  ›  salocinx

为什么这个小C程序会在ESP32上崩溃?

c
  •  2
  • salocinx  · 技术社区  · 7 年前

    我与Esspresif ESP32 WROOM委员会合作。我试图分析使用GDB硬件调试器得到的错误,但我只收到错误发生的行,没有错误描述。

    这是我的小程序:

    typedef unsigned char u08;
    
    void app_main() {
      static char *mac_str = "00:00:00:00:00:00";
      static u08 mac_addr[6] = {0x1a, 0x11, 0xaf, 0xa0, 0x47, 0x11};
      net_dump_mac(mac_addr);
    }
    
    void net_dump_mac(const u08 *in) {
        int pos = 0;
        for (int i=0; i<6; i++) {
            byte_to_hex(in[i], (u08 *)(mac_str+pos));
            pos += 3;
        }
        uart_send(mac_str);
    }
    
    void byte_to_hex(u08 in, u08 *out) {
        out[0] = nibble_to_hex(in >> 4);       // <= crash occurs here !
        out[1] = nibble_to_hex(in & 0xf);
    }
    
    u08 nibble_to_hex(u08 in) {
        if (in < 10)
            return '0' + in;
        else
            return 'A' + in - 10;
    }
    

    1 回复  |  直到 7 年前
        1
  •  7
  •   Paul Ogilvie    7 年前

    char *mac_str = "00:00:00:00:00:00"; 将文本字符串指定给 mac_str . 在许多体系结构中,文本是只读的。试图修改它将导致内存管理器不允许它,通常会导致segfault或其他异常发生。

    相反,要:

    char mac_str[] = "00:00:00:00:00:00";
    

    这将创建一个数组,该数组使用右侧的文本进行初始化,并将其复制到数组中。数组的大小为文字字符串的大小,包括null终止符。此数组变量可修改。