为了构建嵌套的 TLV 元素(例如,6F1A840E315041592E5359532E4444463031A5088801025F2D02656E),我使用以下数据结构:
typedef struct Element
{
int16_t nTag; // Tells you if pValue points to a primitive value or constructed one
uint16_t nLength;
void *pValue; // Could be either unsigned char* or TlvElement*
} TlvElement;
如何实现正确释放嵌套 TLV 元素使用的内存的函数?
// Let's build TLV data: 6F04A5020000
TlvElement *pTlvElement = (TlvElement*)malloc(sizeof(TlvElement));
pTlvElement->nTag = 0x6F;
pTlvElement->nLength = 4;
pTlvElement->pValue = malloc(sizeof(TlvElement)); // pValue points to another TLV element
TlvElement *pTlvElementChild = (TlvElement*)pTlvElement->pValue;
pTlvElementChild->nTag = 0xA5;
pTlvElementChild->nLength = 2;
pTlvElementChild->pValue = malloc(2 * sizeof(unsigned char)); // pValue points to a byte array
memset(pTlvElementChild->pValue, 0, 2);
Deallocate(pTlvElement);
//free(pTlvElementChild->pValue);
//free(pTlvElement->pValue);
//free(pTlvElement);