75

When I read BlueZ source code, I often see char arrays defined like this:

// bluez/android/sco-msg.h
static const char BLUEZ_SCO_SK_PATH[] = "\0bluez_sco_socket";

What good is it to define the first element as \0?

PC Luddite
  • 5,883
  • 6
  • 23
  • 39
user1923105
  • 713
  • 5
  • 9
  • 23
    It effectively hides the string from printing or copying with standard functions - Whatever the intention might be. – tofro Jul 11 '16 at 10:16
  • In Bluez, this style arrays are used like: struct sockaddr_un addr; memcpy(addr.sun_path, BLUEZ_SCO_SK_PATH, sizeof(BLUEZ_SCO_SK_PATH)); What would the socket path looks , /dev/socket/?bluez_sco_socket ? or it can't be seen using "ls" command ? – user1923105 Jul 11 '16 at 10:32

1 Answers1

116

In your particular case this array is used as pathname for a PF_LOCAL socket; see here. And leading NUL is used to point that address is an abstract one. From man 7 unix:

an abstract socket address is distinguished by the fact that sun_path[0] is a null byte ('\0').

And this is the only reason why the first element is \0.

edmz
  • 8,220
  • 2
  • 26
  • 45
Sergio
  • 8,099
  • 2
  • 26
  • 52
  • 9
    Might want to quote this as well, for posterity: "[T]he abstract namespace w[as] introduced with Linux 2.2 and should not be used in portable programs." – Kevin Jul 12 '16 at 05:29