0

The strcat function is working fine when called for the first time but when the broker goes down and it's attempting to reconnect it is appending the value twice. I am not able to figure out the problem as i am writing C code for the first time.

void reconnect() {

  while (!client.connected()) {
    const char* cid = clientID.c_str();
    if (client.connect(cid)) {
       const char* sTopic = strcat("clm/",cid);
       client.publish(outTopic, sTopic);
       client.subscribe(sTopic);
    } else {
    // Wait 5 seconds before retrying
    for(int i = 0; i<5000; i++){
      delay(1);
    }
  }
}

}

It is called in the loop method

void loop() {
  if (!client.connected()) {
    reconnect();
  }
}

The value of sTopic for the first time is clm/5C:CF:7F:3D:5B:F6 but when the broker restarts and the client connects again it is clm/5C:CF:7F:3D:5B:F65C:CF:7F:3D:5B:F6

What could be the reason for the same ?

1

strcat won't allocate any memory for the new string. So what really happens is that the location where the string constant "clm/" is stored gets the id appended.

In other words the second time around it's as if you passed "clm/5C:CF:7F:3D:5B:F6" as first parameter.

To fix that you need to supply a proper buffer for strcat to do its work:

if (client.connect(cid)) {
   char[64] sTopic ={0};
   strcat(sTopic , "clm/");
   strcat(sTopic , cid);
2

Appends a copy of the source string to the destination string.

source

Congratulations, you've broken your string literal. Either stick to using String or make sure you allocate a string properly and then concatenate into that.

0

You have to cat only one string per time. Your assumption is that it performs

dest = strcat(string_1, string_2)

However, it is:

dest = strcat(dest, string_1)

So you should use

char sTopic[256]; // Max possible length

...

strcpy(dest, "clm/");
strcat(dest, cid);

This will first copy "clm/" to dest, than cid will be concatenated.

(code not tested)

See reference: reference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.