Bug in Time.h

It looks like the string functions in Time.h share a single output buffer so you may or may not get what you expect depending on timing.

Don't bitch about using sprintf(). You can reproduce the bug with Serial.print()

sprintf(adr,"%s, %s %u, %u", dayStr(weekday()), monthStr(month()), day(), year());

In this case the day of the week gets overwritten by the name of the month and prints "September September 30, 2012" If you reverse the calls the month will be overwritten by the day.

I'm not sure it's really a bug. Any library that returns a string has to do one of:

  • Dynamically allocate memory, which you then have to free afterwards.
  • Use a static buffer, meaning you can't have two calls like you have done above.
  • Accept a buffer passed in from the caller, and write to that.

So there's no "cheap" fix. The closest fix would be for weekday() and monthStr() to use separate buffers, but then those static buffers are always there, which on a processor with a small amount of memory isn't optimal. And even that would fail if you happened to call weekday() twice.

Your simplest fix here is to call each one on its own line, and strcat them together into your own buffer.

Doesn't dynamically allocated memory get freed when it goes out of scope? I think that how strings work, otherwise you'd need some kind of String.delete() function and Strings would really suck. I know you feel they suck anyway. Just sayin.

Time.h doesn't seem to be Arduino software. It's in the playground so perhaps I should be talking to the author.

TheNorm:
Doesn't dynamically allocated memory get freed when it goes out of scope? I think that how strings work, otherwise you'd need some kind of String.delete() function and Strings would really suck. I know you feel they suck anyway. Just sayin.

Well you don't (generally, although you could) dynamically allocate Strings. the String class does allocate and deallocate chars internally, though, and it makes sure to deallocate everything in its destructor, which is called when a statically allocated String goes out of scope.

TheNorm:
Doesn't dynamically allocated memory get freed when it goes out of scope?

No. Not as such. More-or-less the whole point of dynamically allocated memory is you get to keep it for as long as you want.

As WizenedEE said though, if you use a String object, and the String object goes out of scope, its destructor frees the memory it used.

In your example though, if the Time class returned a String it would be out of scope the moment it got returned.