1

I'm getting an unexpected extra character added to the serial monitor print line only when I initialize an SD card in the code.

Normal

The code below gives me this expected result in the serial monitor:

Serial Monitor

23:31:12.745 -> inputString: abc

Code

const int BUF_DIM = 3;
char inputString[BUF_DIM];

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  
  inputString[0] = 'a';
  inputString[1] = 'b';
  inputString[2] = 'c';

  Serial.print("inputString: ");
  Serial.println(inputString);
}

void loop() {
}

Unexpected Character

However, the serial monitor prints an unexpected extra M at the end of inputString's value abc when I add initialization of an SD card.

Serial Monitor

23:24:30.319 -> Initializing SD card...initialization done.
23:24:30.319 -> inputString: abcM

Code

#include <SPI.h>
#include <SD.h>


File myFile;

const int BUF_DIM = 3;

char inputString[BUF_DIM];


void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  //-------------Toggle this block to see the M dissapear-----------
  Serial.print("Initializing SD card...");
  if (!SD.begin(5)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  myFile = SD.open("DATA.TXT");
  //-------------Toggle this block------------
 
  
  inputString[0] = 'a';
  inputString[1] = 'b';
  inputString[2] = 'c';


  Serial.print("inputString: ");
  Serial.println(inputString);
}

Why is this happening and how can I get the serial monitor to behave as expected with the SD card.

1 Answer 1

2
const int BUF_DIM = 3;

char inputString[BUF_DIM];
...

  inputString[0] = 'a';
  inputString[1] = 'b';
  inputString[2] = 'c';

...

  Serial.println(inputString);

You have allowed three characters in your array and indeed put three characters there, however you have not put a "null terminator" there at the end (nor is there room for one) so you will naturally get garbage at the end of the string until the processor happens to find a 0x00 byte.

Put it another way, how does the code know to print three characters and not 20 characters? The answer is that the underlying function (Serial.println in this case) looks for a null-terminator.

You need to read up on how null-terminated strings work.

1
  • Ahh yes inputString[2] = '\0'; fixed the issue. Didn't know about null-terminators. Thanks! Commented Feb 4, 2022 at 5:20

Your Answer

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

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