结构的内存大小

时间:2019-10-18 23:46:11

标签: c++ c

我具有以下结构。

function createClosure (){

  var secret = "shhhhh";

  return function inner(){
    debugger;
    console.log(secret);
  };

};

var innerFunction = createClosure();

innerFunction();

不带填充的此结构的大小应为83,但是在64位处理器上编译时,大小显示为84。 编译器为pdp_address [10]分配了一个额外的字节。不确定为什么要分配此额外的字节。有人可以让我知道原因吗?

我用以下代码检查了每个成员的偏移量:

    typedef struct {
        int8_t     tmsi[4];        /**< TMSI value. */
        int8_t     ptmsi[4];       /**< PTMSI value. */
        int8_t     gprs_attach_status;
        int8_t     rplmn[3];               /**< PLMN info */
        uint32_t T3212_value;
        uint32_t T3312_value;
        uint8_t   cs_reject_cause;
        uint8_t   ps_reject_cause;
        int8_t     qos[28];  /** QoS  parameters for a PDP context. */
        int8_t     pdp_addr_len;
        int8_t     pdp_address[10];
        uint16_t apn_addr_len;   /**< APN address length. */
        int8_t     apn_address[20];   /**< APN address. */
    }nas_ftd_umts_nas_info_s_type_v01 ;
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) 

    int main()
    {
        temp a; 
        test_ping_req_msg_v01 t;
        nas_ftd_umts_nas_info_s_type_v01 info;
        nas_ftd_umts_network_info_s_type_v01 lte;
        nas_umts_ftd_info_ind_msg_v01 ftd;
        cout << sizeof(info) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, ptmsi) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, gprs_attach_status) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, rplmn) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, T3212_value) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, T3312_value) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, cs_reject_cause) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, ps_reject_cause) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, qos) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, pdp_addr_len) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, pdp_address) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, apn_addr_len) << endl;
        cout << OFFSETOF(nas_ftd_umts_nas_info_s_type_v01, apn_address) << endl;
    }

1 个答案:

答案 0 :(得分:6)

uint16_t的对齐要求是从偶数地址开始。在不填充pdp_address[10]的情况下,您有61个字节(即奇数),直到apn_addr_len,因此编译器用一个字节填充pdp_address,以将apn_addr_len放入偶数地址。