The following code

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


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

  Serial.print("LED colour: ");

  Serial.print("Max mA:      ");

  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);

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, 2017 at 18:57
  • Please add the declaration of msg. The string buffer might be too small. Dec 3, 2017 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, 2017 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, 2017 at 20:14
  • 1
    Hold off for a bit, thanks, guys. I've got the code working now but I'm struggling to find what the original problem was. The stripped down version ran fine. More later and I'll post my findings.
    – Transistor
    Dec 5, 2017 at 17:19


Your Answer

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

Browse other questions tagged or ask your own question.