简体   繁体   中英

Need help resetting some structures in C

I have filled the following structures with values, I don't know how to make them empty again, especially the last two since they contain pointer values. Any help is appreciated.

struct HEADER
{
   unsigned short id; 
   unsigned char rd :1; 
   unsigned char tc :1; 
   unsigned char aa :1; 
};


struct QUESTION
{
   unsigned short qtype;
   unsigned short qclass;
};

struct R_DATA
{
   unsigned short type;
   unsigned short class;
   unsigned int ttl;
   unsigned short data_len;
};

struct RES_RECORD
{
   unsigned char *name;
   struct R_DATA *resource;
   unsigned char *rdata;
};

typedef struct
{
    unsigned char *name;
    struct QUESTION *ques;
} QUERY;

In order to fill these values you would have allocated memory to these pointers free() them accordingly. For example:

typedef struct 
{
  unsigned char *name;
  struct QUESTION *ques;
}QUERY;

QUERY *q = malloc(sizeof(QUERY));
q->name = malloc(20);
q->ques = malloc(sizeof(struct QUESTION));

//Filling the values and using them when done you need to free the allocated memory

Now free them

free(q->name);
q->name = NULL;
free(q->ques);
q->ques = NULL;
free(q); 
q = NULL;

Because of the nested structs and pointers, you can't use bzero or memset(). You just have to set the values to 0 and free them and set them to NULL in the right order. In other words, don't NULL out a reference to anything containing an unfreed pointer.

Straightforward stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM