如何使用char*成员为结构分配内存

Ang*_*ber 3 c memory-management

我的结构看起来像这样:

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 */
};
Run Code Online (Sandbox Code Playgroud)

此结构使用联合来保存一些不同的数据类型.我有一个alloc函数,它为堆上的struct分配内存.我是否正确地认为如果我分配一个整数类型(即联合上面的前四种类型)我只需要按如下方式分配:

tlv_msg* msg = malloc(sizeof(tlv_msg));
Run Code Online (Sandbox Code Playgroud)

sizeof(tlv_msg)返回24.我假设这是足够的字节来保存union中的最大数据类型以及其他数据成员.(不知道为什么24 - 有人可以解释吗?).

但是如果要存储的数据类型是指针类型,例如char*,那么我还需要这样做:

msg->strval = (char*)malloc(sizeof(string_length+1);
Run Code Online (Sandbox Code Playgroud)

这对我来说是有意义的,这似乎有效,但只是想检查.

Mac*_*ade 5

那是完全正确的.

也就是说,您可能希望创建辅助函数,以帮助您处理此问题.

例如:

tlv_msg * new_tlv_msg( void );

/* There, you need to free struct members, if applicable */
void delete_tlv_msg( tlv_msg * msg ); 

/* Here you may copy your string, allocating memory for it */
tlv_msg_set_strval( tlv_msg * msg, char * str );
Run Code Online (Sandbox Code Playgroud)

实施可能是(基本的,当然)

tlv_msg * new_tlv_msg( void )
{
    return calloc( sizeof( tlv_msg ), 1 ); 
}

void delete_tlv_msg( tlv_msg * msg )
{
    if( msg->strval != NULL )
    {
        free( msg-strval );
    }
    free( msg );
}

tlv_msg_set_strval( tlv_msg * msg, char * str )
{
    if( msg->strval != NULL )
    {
        free( msg-strval );
    }
    msg->strval = strdup( str );
}
Run Code Online (Sandbox Code Playgroud)