0

The following code

  int i;
  char msg[16]; // Serial data.

  Serial.println();
  Serial.println("===============");

  sprintf(msg, "Sequence:  %4d", runNum);
  Serial.println(msg);

  Serial.print("LED colour: ");
  Serial.println(colours[colour]);

  Serial.print("Max mA:      ");
  Serial.println(mAmax);

  Serial.println("  mA    mV");
  for (i = 1; i <= mAmax; i++) {
    sprintf(msg, "%4d", i);          // <--- Line 1.
    Serial.print(msg);               // <--- Line 2.
    sprintf(msg, "%6d", i * 3);
    Serial.println(msg);
    delay(50);
  }

crashes after the first pass as shown below:

===============
Sequence:     1
LED colour: red
Max mA:      30
  mA    mV
   1     3

If I comment out "Line 1" and "Line 2" the loop runs correctly.

I suspect that something odd happens with either the two sprintf calls or the Serial.print / Serial.println calls in quick succession.

Can anyone spot an error or know of an issue that I've missed?

Development environment: create.arduino.cc

  • 2
    Not from that snippet, no. You need to show your full code, or a version of the code that at least compiles and demonstrates the problem. As it stands we cannot know what is happening because we don't know what your code is doing. What are your variable types? What values do they contain? What else is going on with your code that could have a bearing on it? – Majenko Dec 3 '17 at 18:57
  • Please add the declaration of msg. The string buffer might be too small. – Mikael Patel Dec 3 '17 at 19:34
  • I forgot about the declaration. I've added that. I've also stripped down my code to the snippet above plus the setup, etc., and it works. Darn! More digging. I'll update later when I have more info. – Transistor Dec 3 '17 at 20:08
  • 1
    %4d does not limit the maximum size. When the number is 20000 the whole 20000 is printed and your buffer will overflow. You assume that the loop runs correctly when those two lines are commented out. I doubt that. Data on stack that is overwritten or ram problems or heap overflow is not always detected. We still need a full working sketch that shows the problem. – Jot Dec 3 '17 at 20:14
  • avr-libc does have snprintf(), or you could check the value for limits before sprintfing it. – Ignacio Vazquez-Abrams Dec 3 '17 at 20:24

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.