5

私は、構造体の次の使用が行われている会社で初めてです。

#include <stdio.h>
#include <string.h>

typedef unsigned char uint8;
typedef signed char int8;
typedef unsigned short int uint16;
typedef signed short int int16;

typedef struct padded_t {
    int8 array0[11];
    int8 array1[4];
    uint16 len2;
    int8 array2[25];
    uint16 len3;
    int8 array3[6];
    // many more len/arrays follow
} padded_t;

int main(int argc, char** argv)
{
    padded_t foo;
    memset((void*)&foo, 0, sizeof(padded_t));

    int8* str = "foobar";
    int16 size = (int16)strlen(str);

    int8* ptr = (int8*)&foo.len2;

    // please note that the memcpy references only the pointer to len
    // are the following couple of lines safe?
    memcpy ((void*)ptr, &size, 2);
    memcpy ((void*)&ptr[2], (void*)str, size);

    printf("%d\n", foo.len2);
    printf("%s\n", foo.array2);

    return 0;
}

アラインメントとパディングについていくつかのことを知っており、コンパイラ (ARM9 デバイスの場合は gnu C99) がパディングを追加して、構造体をアラインさせると想定しています。

しかし、このコードは安全ですか? 私が理解しているように、他の構造体メンバーに関係なく、変数の直後に変数が続く
限り安全です。uint16 lenint8 array[]

uint16 の前のサイズが奇数の場合にのみ、パディングを追加しますか?
この使い方は正しいですか?さらに重要なことに、それは安全ですか?

4

2 に答える 2