Wrong destination size for strncpy

111 views Asked by At

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.

0

There are 0 answers