Newbie sprintf question

Hello,

I'm relatively new to C++ and am struggling a bit with char arrays (and pointers) and have written some code that isn't working (more detail below). I've stripped a bigger sketch down to the bare essentials to reproduce the problem I'm getting. Here's the code:

#include <ESP8266WiFi.h>

//MQTT Topics---------------------------------------------------------------
char *mqttROOT = "/alongnamethatdoesntmatter/";
char *mqttConnect = "connect/";
//==========================================================================

//Other variables-----------------------------------------------------------
const char *myID = "ABC";
//==========================================================================


void setup() {
  Serial.begin(115200);
  
   //Create a temporary variable to build the topic to publish to
  char Topic[sizeof(mqttROOT) + sizeof(myID) + sizeof(mqttConnect) + 2];
  sprintf(Topic, "%s%s/%s\0", mqttROOT, myID, mqttConnect);

  //Create a temporary variable to hold the message to publish, in this case an IPAddress
  IPAddress ipAddr = WiFi.localIP();
  char Msg[16];                     //Buffer big enough to hold the IP address
  sprintf(Msg, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);

  Serial.print("Publishing to topic ");
  Serial.println(Topic);
}

void loop() {
 
}

(Note that you can replace the <ESP8266WiFi.h> with <WiFi.h> if you don't have an ESP8266 - it's only needed for the IPAddress class)

When I run this I get the following in the Serial Monitor:

Publishing to topic /alongnamethatdoð…þ?

I'm guessing that this is to do with memory sizes but I'm not knowledgeable enough to understand the whys and wherefores (although I am keen to learn).

Could somebody explain why it's printing out more characters than I want?

Also, if I remove the following code

IPAddress ipAddr = WiFi.localIP();
char Msg[16];                     //Buffer big enough to hold the IP address
sprintf(Msg, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);

It crashes the ESP8266 (which I again assume is due to some sort of buffer overrun).

Any help greatly appreciated.

Thanks,

Ben.

Sizeof returns the size of the pointer. It doesn't walk the length of your string to find the terminating character. So you end up writing past the end of the too-short Topic string, which damages other variables that you are using.

Use strlen() or one of its cousins to find the length of a string.