Problem with ESP8266 Web Server [Fixed]

Hey guys,

I have an issue with my WeMos D1 mini board which uses an ESP8266 controller.

Basically I'm running a web server on the board. I loaded an HTML file onto filesystem of the chip and use it's content as the string sent to a client if he sents a GET request. All just like any normal web server.

And almost everything works perfecly normal, except that at the very end of the HTML file the client recieves (after the closing '' tag), there is a string that isn't part of the original file. The string is: '@p???' (the first and second '?' are in a black diamond)

When I output the char[] (the exact same one as I send to the client) to the serial monitor, this string isn't at the end....

This is the (relevant) code:

void handleRoot() {
  digitalWrite(led, 1);
  String path = "/index.html";

  File f = SPIFFS.open(path, "r");
  if(!f) {
    Serial.print("Failed to open File: '");
    Serial.print(path);
    Serial.println("'");
    Serial.println("");
  }

  int charAmt = f.size();
  char temp[charAmt];
  f.readBytes(temp, charAmt);

  server.send(200, "text/html", temp);
  digitalWrite(led, 0);

  Serial.println(charAmt);
  for(int i = 0; i < charAmt; i++) {
    Serial.print(temp[i]);
  }
}

Thanks for your time and help already!!!

P.S. Please let me know if I missed any relevant information :slight_smile:

My suspicion is that you are sizing temp[] for the string length but not leaving room for the all important null terminator. So when you send the string to the client it doesn't know where the end of the string is and continues on into some random area of memory, thus the gibberish. Your Serial output works differently because that for loop ensures that it will stop at the end of the string. I suspect if you had simply done Serial.print(temp) you would see the same result as what the client received.

Try the following code that ensures you get a null terminator:

void handleRoot() {
  digitalWrite(led, 1);
  String path = "/index.html";

  File f = SPIFFS.open(path, "r");
  if(!f) {
    Serial.print("Failed to open File: '");
    Serial.print(path);
    Serial.println("'");
    Serial.println("");
  }

  int charAmt = f.size();
  char temp[charAmt+1];
  f.readBytes(temp, charAmt);
  temp[charAmt] = 0;  // Add null terminator

  server.send(200, "text/html", temp);
  digitalWrite(led, 0);

  Serial.println(charAmt);
  for(int i = 0; i < charAmt; i++) {
    Serial.print(temp[i]);
  }
}

Thank you so much!

That totally solved my problem^^

Probably this is exactly what happens when someone that usually codes in Java and PHP tries to write some C...

Well I won't forget the null terminator in the future...

Thanks again!

Louis