0

I'm was using this function in Arduino to pad out a string to 40 characters (the width of my LCD), so that in the process of writing it it clears any characters left behind from the last write.

Problem is when I use it, it stops my RF24 module from being able to send...(everything else still runs, and it recieves) weird I know...

  void printLine(char* line){

      sprintf(line, "%-40s", line);
      lcd.writeString(line);  

    }

It was pointed out that should not write into line from line, i corrected this, but same problem. This function also has the same problem:

void emptyLine(){

  sprintf(line, "%-40s", "");
  lcd.writeString(line);  

}

And here is declaration of 'line' (from top of code)

char line[lcdCols];
Hayden Thring
  • 1,718
  • 17
  • 25
  • possible duplicate of [Is sprintf(buffer, "%s \[…\]", buffer, \[…\]) safe?](http://stackoverflow.com/questions/1283354/is-sprintfbuffer-s-buffer-safe) – alk Jun 08 '14 at 09:07
  • With your new code, there's simply not enough information to go on. Where is `blank` defined? What is `lcd.writeString()`? – Oliver Charlesworth Jun 08 '14 at 09:31
  • sorry about blank, it was from trial of using 2 bufers, after initial answer, i have corrected it to original code. lcd.writeString comes from: https://code.google.com/p/arduino-t6963c/source/browse/T6963_Lib/T6963.h – Hayden Thring Jun 08 '14 at 09:34
  • 3
    Ok, so now it's apparent that you forgot to leave room for the null terminator... – Oliver Charlesworth Jun 08 '14 at 09:36
  • I changed 40 to 39 and its working again :) thanks, I forgot about that too. – Hayden Thring Jun 08 '14 at 09:57

1 Answers1

1

You're trying to write into the same character buffer that you're reading from.

From the C99 standard:

sprintf [...] If copying takes place between objects that overlap, the behavior is undefined.

In practice, this is probably just causing an infinite loop.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680