2

Visual Studio Code 1.73.1, PlatformIO 6.1.5, toolchain-xtensa-esp32 8.4.0. In a third-party library there are these lines of code:

#define TZNAME_MAX_LEN 50
#define TIMEZONE_MAX_LEN 50

typedef struct
{
    WiFi_Credentials WiFi_Creds[NUM_WIFI_CREDENTIALS];
    char TZ_Name[TZNAME_MAX_LEN]; 
    char TZ[TIMEZONE_MAX_LEN];    
    uint16_t checksum;
} WM_Config;

WM_Config WM_config;

// ...

String tempTZ = ESPAsync_wifiManager.getTimezoneName();

if (strlen(tempTZ.c_str()) < sizeof(WM_config.TZ_Name) - 1) 
    strcpy(WM_config.TZ_Name, tempTZ.c_str());
else
    strncpy(WM_config.TZ_Name, tempTZ.c_str(), sizeof(WM_config.TZ_Name) - 1);

sizeof(WM_config.TZ_Name) - 1 evaluates to 49. But the compiler returns this warning:

'char* strncpy(char*, const char*, size_t)' writing 49 bytes into a region of size 32 overflows the destination [-Wstringop-overflow=]

I don't understand why it thinks the destination has a size of 32 bytes, while it is 50 bytes long, actually.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Mark
  • 4,338
  • 7
  • 58
  • 120
  • 1
    What is `String` and where does it come from? – Karl Knechtel Nov 22 '22 at 09:04
  • @KarlKnechtel https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/ – Mark Nov 22 '22 at 09:05
  • Three things: First of all why not `tempTZ.length()` instead of `strlen(tempTZ.c_str())`? Secondly, your current call to `strncpy` will *not* add the string terminator. Thirdly, why the size check at all? It's not needed, as `strncpy` will stop at the string null-terminator in the source string just like `strcpy`. – Some programmer dude Nov 22 '22 at 09:05
  • @Someprogrammerdude I agree with you but it's not my code. There a link to the git repository of this library. My question is about where the 32 comes from. – Mark Nov 22 '22 at 09:06
  • 2
    Perhaps a decimal versus hexadecimal mixup somewhere? Hexadecimal `0x32` is decimal `50`. The original author perhaps wrote `32` by mistake when she or he was planning to write `0x32`? You have to look through the code more. And if possible ask the original author, or possibly submit a bug report. – Some programmer dude Nov 22 '22 at 09:07
  • Maybe a compiler bug? What happens if you copy to `&WM_config.TZ_Name[0]` or even store the pointer in a `char*` variable and use that for the copy? – paddy Nov 22 '22 at 09:10
  • 2
    There are a lot of bugs in bugzilla around this warning. e.g. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94335 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92955... and a lot more... – Klaus Nov 22 '22 at 09:15
  • 1
    Can't reproduce. A toolchain bug? – n. m. could be an AI Nov 22 '22 at 09:41

0 Answers0