C array of problems with initializing structures when using macros

Why adsafe_tags [1] does not receive the correct initialization?

// local string (via static)
#define SSTRL(varname, val) \
    static const char varname[] = val

#define SSTRLEN(var) \
    (sizeof(var) - 1)

struct scs_data_tag
{
    uint16_t key_size;
    uint16_t val_size;
    char     data[];
};

SSTRL(ADSAFE_KEY, "p.as.rsa");
SSTRL(ADSAFE_VAL_BAD, "0");
SSTRL(ADSAFE_VAL_GOOD, "1000");
#define ADSAFE_KV_BAD "p.as.rsa0"
#define ADSAFE_KV_GOOD "p.as.rsa1000"

struct scs_data_tag adsafe_tags[] = {
    {SSTRLEN(ADSAFE_KEY), SSTRLEN(ADSAFE_VAL_BAD), ADSAFE_KV_BAD},
    {SSTRLEN(ADSAFE_KEY), SSTRLEN(ADSAFE_VAL_GOOD), ADSAFE_KV_GOOD}
};

and in gdb I get the following:

(gdb) p adsafe_tags
$7 = {{key_size = 8, val_size = 1, data = 0x8ce664 <adsafe_tags+4> "p.as.rsa0"}, {key_size = 11888, val_size = 29537, data = 0x8ce668 ".rsa0"}}
+3
source share
2 answers

You did not specify a member size data struct scs_data_tag. This declares a member of the C99 flexible array . This member has a size of 0 by default, and you need mallocmore than the actual size of the structure so that it can contain data.

According to the standard, struct scs_data_tagit should not be an element of an array (since it contains a flexible element of an array). But this is supported by some compilers as an extension.

If you give this array a sufficiently large size (e.g. char data[40]), your code should work.

+2

interjay. adsafe_tags[1].key_size = 11888, 0x2e70 , ASCII p (= 0x70) . (= ​​0x2e), "p.".

, adsafe_tags[1].val_size = 29537, 0x7361 "as", .

, adsafe_tags[0].data .

, , .

+1

All Articles