9 years, 9 months ago.

Strange behavior when using strftime function

I have a program I'm developing that communicates with the PC over USB serially via pc.printf I'm trying to do some things with the real time clock.

Here is a code snippet:

  1. define btsize 32

char bufftime[btsize];

strftime(bufftime, btsize, "%m%d%y%I%M%S", localtime(&seconds));

pc.printf("Time = %s", bufftime);

This works just fine when I run it, but here's the strange part: If I include the code above in the program, other parts of the program, totally unrelated to this, locks up the chip when trying to send data to the pc. It always locks up after sending exactly 16 characters. This happens whether or not the above code is ever executed. If I comment out the strftime statement, it all works fine. Also, if I change the buffer size to a larger value, it all works fine. As I said, it doesn't matter if the code is actually executed, all that seems to matter is that it is included in the compile and the buffer size is 32 bytes.

Is this a compiler bug? I can't understand why code that is not even executed would have an effect on some other unrelated code in the program.

Have you tried increasing your buffer size? I had a similar issue, increasing this stopped the problem. I'm not sure if the buffer needs extra space specified for the NULL characters or whether the compiler deals with this.

Ahh just read the rest of your question, the extra space will be needed then. The pointers to the ram stack will probably overlap by one or two bytes with other parts of your program code if this is short.

posted by Paul Staron 06 Feb 2015

Yes, increasing the buffer size fixes the problem. I'm just having a problem understanding why code that is compiled but never executed has an effect on code in a completely unrelated part of the program, especially when the effect is to completely lock up the processor. Makes me worry about other weird side effects biting me down the road.

posted by Chuck Davis 08 Feb 2015
Be the first to answer this question.