TLV可变结构体

ExpandedBlockStart.gif 代码
 1  #include  < stdio.h >
 2  #include  < malloc.h >
 3  #include  < string .h >
 4 
 5  typedef unsigned  char  UCHAR;
 6  typedef  char  CHAR;
 7  typedef unsigned  long  ULONG;
 8  typedef unsigned  int  USHORT; 
 9  #include  < stdio.h >
10  #include  < string .h >
11 
12 
13 
14  typedef  struct  STRUCT_TLV
15  {
16      USHORT usType;
17      USHORT usLen;
18      UCHAR ucValue[ 0 ];
19  }TLV;
20 
21  int  main() 
22  {
23      UCHAR  * pdata  =  NULL;
24      TLV  *  pstTLV  =  NULL;
25       const  CHAR  *  p1  =   " ab " ;
26       const  CHAR  *  p2  =   " cde " ;
27 
28      printf( " sizeof(TLV)=%d " sizeof (TLV));
29 
30      pdata  =  (UCHAR  * )malloc( 2   *  ( sizeof (TLV)  +   sizeof (UCHAR)));  /*此处虽然没按照所用空间申请,但结果正确,建议不这样做*/
31       if  (pdata  ==  NULL)
32      {
33           return   0 ;
34      }
35 
36      pstTLV  =  (TLV  * )pdata;
37 
38      pstTLV -> usType  =   0x01 ;
39      pstTLV -> usLen  =  strlen(p1)  +   1 ;
40      memcpy(( void   * )pstTLV -> ucValue, ( void   * )p1, pstTLV -> usLen);
41      printf( " \r\n TLV1: "
42              " \r\n usType=%u "
43              " \r\n usLen=%u "
44              " \r\n ucValue=%s\r\n " ,
45             pstTLV -> usType, pstTLV -> usLen, pstTLV -> ucValue);
46 
47      pstTLV ++ ;
48      pstTLV -> usType  =   0x02 ;
49      pstTLV -> usLen  =  strlen(p2)  +   1 ;
50      memcpy(( void   * )pstTLV -> ucValue, ( void   * )p2, pstTLV -> usLen);
51      
52      printf( " \r\n TLV2: "
53           " \r\n usType=%u "
54           " \r\n usLen=%u "
55           " \r\n ucValue=%s\r\n " ,
56             pstTLV -> usType, pstTLV -> usLen, pstTLV -> ucValue);
57 
58 
59       return   0 ;
60  }
61 

  pdata = (UCHAR *)malloc(2 * (sizeof(TLV) + sizeof(UCHAR)));  /*此处虽然没按照所用空间申请,但结果正确,建议不这样做*/
  虽然后面的操作越界,但结果还是对的,不知为什么。

  但最好还是按照实际所用申请。

pdata = (UCHAR *)malloc(2 * sizeof(TLV) + 3 * sizeof(UCHAR)+ 4 * sizeof(UCHAR)); 

 

转载于:https://www.cnblogs.com/lihongsheng0217/archive/2011/02/16/1956527.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值