Hi, I am using IDE 1.6.9 (under Windows 10) and found the problem in a complex sketch loaded onto a Mega 2560. I then ported a subset of code (minimalised and simplistic) onto a Uno which also demonstrates the problem.
This sketch is shown below and has a group of snprintf() calls at the end, only one of which is active at any given time ( in order to diagnose the problem)
const size_t sizeBuffer = 140;
char g_szBuffer[sizeBuffer];
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
snprintf(g_szBuffer,sizeBuffer,"Hello world");
Serial.print(F("Contents of g_szBuffer after initialization [prior to sendEmail()] is :")); Serial.println(g_szBuffer); //... which is correct i.e. "Hello again"
sendEmail(g_szBuffer);
}
void loop() {
// put your main code here, to run repeatedly:
}
//************************************************************************
byte sendEmail(const char szTextIn[]) // 20190930
{
Serial.println("In Sendmail");
Serial.print(F("szTextIn :")); Serial.println(szTextIn);
Serial.print(F("g_szBuffer before initialisation [in sendEmail] :")); Serial.println(g_szBuffer);
int iRet = 0;
snprintf(g_szBuffer,sizeBuffer,"**** Connection failed (msg is %s) - return code = %i",szTextIn,iRet); //original
//Original result: "**** Connection failed (msg is **** Connection failed (msg is ) - return code = 0"
//snprintf(g_szBuffer,sizeBuffer,"msg is %s - return code = %i",szTextIn,iRet);
// TEST 1 result: "msg is msg is msg - return code = 0"
//snprintf(g_szBuffer,sizeBuffer," %s - return code = %i",szTextIn,iRet);
// TEST 2 result: " - return code = 0"
//snprintf(g_szBuffer,sizeBuffer,"%s - return code = %i",szTextIn,iRet);
// TEST 3 result: "Hello world - return code = 0" AS EXPECTED
Serial.println(F("Result of snprintf() ... "));
Serial.println(g_szBuffer);
return 0;
}
The serial monitor output for the "original" snprintf() is shown below:
Contents of g_szBuffer after initialization [prior to sendEmail()] is :Hello world
In Sendmail
szTextIn :Hello world
g_szBuffer before initialisation [in sendEmail] :Hello world
Result of snprintf() ...
**** Connection failed (msg is **** Connection failed (msg is ) - return code = 0
The "error" is that the text preceeding the %s appears to be repeated insted of the %s rather than szTextIn.
For convenience, I have annotated the result of each test below the appropriate snprintf() call, rather than showing multiple SM.
I have also found that correct operation occurs if the target of the snprintf is a local var to the function sendEmail() rather than the current global var g_szBuffer.
I just don't understand what is happening here as I believe that my usage of snprintf() is correct