Search code examples
delphirecord

Is extra space allocated for variant records?


I'm working with the variant record below. The variable instance is Kro_Combi. SizeOf(Kro_Combi) reports 7812 bytes. SizeOf(Kro_Combi.data) reports 7810 bytes. The sum of the SizeOf of all the other data structures composing the "non-directmode" case of the variant record also adds to 7810 bytes.

Why is there a two byte difference? I would like to have the two variant exactly overlay each other.

TKro_Combi = record
  case directmode:boolean of
    true : (
      data : array[0..7809] of byte
           );
    false : (
      Combi_Name            : array[0..23] of char;                //24
      Gap1                  : array[0..63] of byte;                // 24-87 (64)
      Ins_Effect_Group      : array[1..12] of TIns_Effect_Params;  //74 each,   (Ins_Effect_Data=9 bytes)  74*12 = 888
      Mast_Effect_Params    : array[0..229] of byte;               // 976-1205 : 230 bytes
      Vect_Aud__Drum_Params : array[0..97] of byte;                //1206-1303  : 98 bytes
      Karma_Common          : array[0..509] of byte;               //1304-1813 : 510 bytes
      Karma_Module          : array[0..3] of TKarma_Module;        //1814-2557 : 744 bytes each  Total span 1814 - 4789 = 2976 bytes total
      Common_Params         : array[0..11] of byte;                //4790-4801 = 12 bytes
      Timbre_Group          : array[1..16] of TTimbre_Params;   )  // 4802 -4989 = 188 bytes each,  16 Timbres, 4802-7809 = 3008 bytes total for all
  end;

Solution

  • First of all, there needs to be space for the directmode field. If you really want the record to have size 7810 bytes then you should remove that field. The other byte will be due to internal alignment and padding of the false part of the variant record. I can't yet quite work out where it comes from. No matter, you simply want to use a packed record to avoid any padding bytes.

    TKro_Combi = packed record  
    case boolean of
    true : (
      data : array[0..7809] of byte
           );
    false : (
      Combi_Name            : array[0..23] of char;                //24
      Gap1                  : array[0..63] of byte;                // 24-87 (64)
      Ins_Effect_Group      : array[1..12] of TIns_Effect_Params;  //74 each,   (Ins_Effect_Data=9 bytes)  74*12 = 888
      Mast_Effect_Params    : array[0..229] of byte;               // 976-1205 : 230 bytes
      Vect_Aud__Drum_Params : array[0..97] of byte;                //1206-1303  : 98 bytes
      Karma_Common          : array[0..509] of byte;               //1304-1813 : 510 bytes
      Karma_Module          : array[0..3] of TKarma_Module;        //1814-2557 : 744 bytes each  Total span 1814 - 4789 = 2976 bytes total
      Common_Params         : array[0..11] of byte;                //4790-4801 = 12 bytes
      Timbre_Group          : array[1..16] of TTimbre_Params;   )  // 4802 -4989 = 188 bytes each,  16 Timbres, 4802-7809 = 3008 bytes total for all
    end;