title: How to allocate memory for a struct with char* member
body: <p>My struct looks like this:</p>
  
  <pre><code>struct tlv_msg
  {
     uint8_t datatype;   //type of data
     /* data stored in a union */
     union{
       int32_t s32val;          /*  int */
       int64_t s64val;          /*  long long */
       uint32_t u32val;         /*  unsigned int */
       uint64_t u64val;         /*  unsigned long long */
       char* strval;            /*  string */
       unsigned char* binval;   /*  any binary data */
     };
  
     uint32_t bytelen;  /* no. bytes of union/data part */
  };
  </code></pre>
  
  <p>This struct uses a union to hold some different data types.  I have an alloc function which allocates memory for the struct on the heap.  Am I correct in thinking that if I am allocating for an integral type (ie the first four types above in union) I only need to allocate as follows:</p>
  
  <pre><code>tlv_msg* msg = malloc(sizeof(tlv_msg));
  </code></pre>
  
  <p>sizeof(tlv_msg) returns 24.  I presume this is enough bytes to hold the largest data type in the union plus the other data members. (not sure why 24 - can someone explain?).</p>
  
  <p>But if the data type to be stored is a pointer type, eg char* then I then need to also do this:</p>
  
  <pre><code>msg-&gt;strval = (char*)malloc(sizeof(string_length+1);
  </code></pre>
  
  <p>That would make sense to me and that seems to work but just wanted to check.</p>