0

I'm running the following Sketch on my Arduino Uno:

const boolean verbose = true;

void debug(const char *s){
    if(verbose){
      char buf[8 + sizeof(s)] = "[DEBUG] ";
      strcat(buf, s);
      Serial.println(buf);
   }
}

void setup() {
  Serial.begin(115200);
  char str[] = "Lorem ipsum dolor sit amet, consetetur sad";

  Serial.print("Size of String: ");
  Serial.println(sizeof(str));
  debug(str);
}

void loop() {
}

The debug() function should be used to print debugging information to Serial. The Sketch like I posted it works wuite fine and prints the following to Serial: Size of String: 43 [DEBUG] Lorem ipsum dolor sit amet, consetetur sad

But when I add one more character to the string (43 chars excluding null terminator) I get the only follwoing on Serial:

Size

This problem does not appaer when defining str as a global varaible. What does cause this issue and how can it be fixed?

2 Answers 2

6

The main issue with your code is:

sizeof(s)

That doesn't return the string length - it returns the size of the char pointer - which is two bytes (on an 8-bit system, 4 on a 32-bit system).

Instead you need to use strlen(s) and add one to it for the NULL character at the end.

if(verbose){
  char buf[8 + strlen(s) + 1] = "[DEBUG] ";
  strcat(buf, s);
  Serial.println(buf);
}

However, what you are doing is pointless. Just print twice:

if(verbose){
  Serial.print(F("[DEBUG] "));
  Serial.println(s);
}

Note the use of the F() macro to ensure that [DEBUG] doesn't waste RAM.

1

sizeof(s) does not do what you thing it does. All it does is take the sizeof of the pointer.

So you end up with Undefined Behavior when you concatenate the strings which means than anything is allowed to happen.

Instead you can do 2 print statements to concat on the serial stream:

void debug(const char *s){
    if(verbose){
      Serial.print(F("[DEBUG] "));
      Serial.println(s);
   }
}
1
  • Beat by 11 seconds... :P
    – frarugi87
    Nov 3, 2017 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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