Serial.print shows some bizarre behaviour.

Hi,

Maybe someone can help explain what's going on here.

#include <EEPROM.h>

void setup() {
  Serial.begin(115200);

  char fn[15];
  *fn = filename();
  Serial.println(fn);
  Serial.println();

  for (byte i = 0; i < 15; i++) {
    Serial.print(fn[i]);
    EEPROM.write(16+i, fn[i]);
  }

  delay(100);
  
  Serial.println();
  char newfn[15];
  for (byte i = 0; i < 15; i++) {
    newfn[i] = EEPROM.read(16+i);
//    Serial.print(EEPROM.read(16+i));
  }
  Serial.println();
}


void loop() {

}

char* filename() {
  char fn[15];
  strcpy(fn, "This is a file");
  return *fn;
}

Output of this sketch, perfectly as expected:

This is a file

This is a file

done

But when I uncomment line 22 I see the garbage as per this screen shot (sorry, couldn't copy/paste this):
screenshot.png
The Serial.println(fn) and Serial.print(fn[i]) get completely messed up somehow. The string of numbers is also not an ASCII encoding of the original string - it looks like the same messed up version of the string that got printed before.

Arduino Pro Mini 5V/16 MHz, Arduino 1.8.5/Linux Mint.

wvmarle:

char* filename() {

char fn[15];
 strcpy(fn, "This is a file");
 return *fn;
}

That function copies the string "This is a file" into the char array fn[] which is on the stack - it is local to this function

When you return a pointer to the string, it is pointing to the stack... which will get overwritten when some other function is called.

Also, this is not correct:

char fn[15];
  *fn = filename();

You could replace that with e.g.

char fn[15];
  getFilename( fn );

// where the function is like:
//
void getFilename( char *fn ) {
  strcpy(fn, "This is a file");
}

Yours,
TonyWilk

TonyWilk:
You could replace that with e.g.

char fn[15];

getFilename( fn );

// where the function is like:
//
void getFilename( char *fn ) {
  strcpy(fn, "This is a file");
}

if you just need a pointer to the array:

char* fn = getFileName();

...
...

char* getFileName() {
  static char filename[20];
  strcpy(filename, (F("This is a file"));
  return filename;
}

Thanks. Makes sense as you explain it.

And it seems to work perfectly.

Pointers continue to bug me... I'm sure that sooner or later I'll really understand the concept, this is yet another step on that road :slight_smile: