[SOLVED] Strange sprintf behavior (not %f)

Hi, I really searched the web and this forum. I found many things about %f which is NOT my case.
The code :

char *str="";
int nb=0;

void setup() {
  Serial.begin(9600);
  Serial.println("Test sprintf");
}

void loop() {
  nb=sprintf(str,"%s\n","Hello");
  Serial.print("=>");
  Serial.println(str);
  delay(3000);
}

Prints 2 lines every 3 seconds instead of one !
It seems that the sprintf function istelf prints on the serial monitor.
This only happens when Serial.print is used (0 lines if not)

Did I missed something ?

Arduino 1.6.5-r2
Windows XP SP3

You missed the fact that str is very, very short.

AWOL:
You missed the fact that str is very, very short.

It is for this example I wanted short.
However the problem seems to be the use of

// Problem with
char *str="";
// Works fine with
char str[20];

But only in this example.
I Will seach my sketch to see if I have similar reasons for not working.

Thanks a lot :slight_smile:

In your first instance, "str"points to a single byte which is a string terminator, which doesn't leave much (aka any) room to write anything.
Your second example has room for 19 characters plus terminator.

Ask yourself this: what is the size of str in your code? (Hint: All pointers in an Arduino IDE use 2 bytes of memory). Now, how much memory does it take to store the string "Hello\n"? (Hint: More than 2 bytes.)

econjack:
Ask yourself this: what is the size of str in your code? (Hint: All pointers in an Arduino IDE use 2 bytes of memory). Now, how much memory does it take to store the string "Hello\n"? (Hint: More than 2 bytes.)

Thanks a lot. You're both right. Changing :

char strCode[12]="";
//to :
char strCode[12];

Fixed the case :slight_smile:
And by the way the linker does not complain anymore with the Error 5 when I remove declaration of an unused variable (I kept to avoid the error).