2

I am working with Esspresif ESP32 WROOM board. I have tried to analyse the error I get with GDB Hardware Debugger, but I only receive the line where the error occurs, no error description.

Here's my small program:

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;
}

Some idea what am I doing wrong here?

salocinx
  • 3,715
  • 8
  • 61
  • 110
  • sorry, I added the definition of `mac_str` ... – salocinx Dec 11 '18 at 15:04
  • 7
    `mac_str` is a *string literal*. You can't modify it. Change it to `char mac_str[]` – Eugene Sh. Dec 11 '18 at 15:04
  • 3
    `static char *mac_str = "00:00:00:00:00:00";` -> `static char mac_str[] = "00:00:00:00:00:00";` – Jabberwocky Dec 11 '18 at 15:04
  • great, changed to `mac_str[]` and now it works. thanks! somebody interested in a short answer? – salocinx Dec 11 '18 at 15:07
  • 1
    Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) – Random Davis Dec 11 '18 at 16:27

1 Answers1

7

char *mac_str = "00:00:00:00:00:00"; assigns a literal string to mac_str. A literal is read-only on many architectures. Trying to modify it will result in the memory manager no allowing it, often causing a segfault or other exception to occur.

Instead, do:

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

This creates an array that is initialized with the literal on the right, which gets copied to your array. The array will be the size of the literal string, including the null terminator. This array variable is modifyable.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41