Find holes in C structs due to alignment

后端 未结 7 2587
难免孤独
难免孤独 2021-02-20 18:26

Is there a way in gcc or clang (or any other compiler) to spit information about whether a struct has holes (memory alignment - wise) in it ?

Thank you.

ps: If

7条回答
  •  暖寄归人
    2021-02-20 18:57

    You need a parser which understands c/c++ structures and includes necessary includes files.

    As replied by @roee-gavirel, I think the easier solution is to create a test program to print out the offsets

    #include 
    #include 
    
    typedef struct tData {
      long   id;       /* 8 bytes */
      char   name[8];  /* 8 bytes */
      float  salary;   /* 4 bytes */
    } tData;
    
    tData d;
    
    int main()
    {
      size_t s_tData  = sizeof(tData);
      size_t s_id     = sizeof(d.id);
      size_t s_name   = sizeof(d.name);
      size_t s_salary = sizeof(d.salary);
    
      printf("sizeof(tData) = %zu\n\n", sizeof(d));
    
      printf("'id'     is at = %3zu  occupies %zu bytes\n",
             offsetof(tData, id), s_id);
      printf("'name'   is at = %3zu  occupies %zu bytes\n",
             offsetof(tData, name), s_name);
      printf("'salary' is at = %3zu  occupies %zu bytes\n",
             offsetof(tData, salary), s_salary);
    
      printf("\n");
    
      if (s_tData != s_id + s_name + s_salary)
        printf("There is/are holes\n");
    
      return 0;
    }
    

提交回复
热议问题