[chbot] Weirdness in parameter interpretation in C lib function

Robin Gilks gb7ipd at gmail.com
Mon Jul 29 23:26:22 BST 2024


Since there are a few C programmers in the group I thought I'd ask
this (interesting?) question

Here is a bit of sample code to illustrate:

----------------------------------------------------------------------------
#include <stdio.h>
#include <stdint.h>


typedef struct
{
char ssid[30];
int8_t rssi;
} ScanResult;

#define NUMRESULTS 50 // how many tracked simultaneously

static ScanResult scandata[NUMRESULTS];

void
main (void)
{
}


char * test (uint8_t index)
{
static char buf[100];

snprintf (buf, sizeof (scandata[index].ssid), "SSID %s\n",
scandata[index].ssid);
return buf;

}
----------------------------------------------------------------------------
Save as test.c; compile with gcc test.c

The warning indicates that the destination buffer may be too small

test.c: In function ‘test’:
test.c:25:56: warning: ‘%s’ directive output may be truncated writing
up to 29 bytes into a region of size 25 [-Wformat-truncation=]
   25 |    snprintf (buf, sizeof (scandata[index].ssid), "SSID %s\n",
scandata[index].ssid);
      |                                                        ^~
test.c:25:4: note: ‘snprintf’ output between 7 and 36 bytes into a
destination of size 30
   25 |    snprintf (buf, sizeof (scandata[index].ssid), "SSID %s\n",
scandata[index].ssid);
      |

This appear to be treating the size parameter in the snprintf as being
the size of the output buffer 'buf' (which is 100 bytes long) but
surely it should be applying the restriction on the format string that
includes  scandata[index].ssid (which is 30 bytes long)

Am I just having brain fade or is that just fundamentally wrong?

-- 
Robin Gilks



More information about the Chchrobotics mailing list