尝试释放结构元素时指针错误

时间:2016-07-27 07:14:12

标签: c

我遇到了一个问题,即释放与结构实例元素相关的内存,定义如下:

typedef struct WebPage {
  char *url;                               // url of the page
  char *html;                              // html code of the page
  size_t html_len;                         // length of html code
  int depth;                               // depth of crawl
} WebPage;

我尝试使用以下内容释放它:

static void setDestroy(set_t *set){

  pair_t *temp2;

  if(set!=NULL&&set->head!=NULL){
    //store the head in a temporary pair
    pair_t *temp = set->head;
    //cycle through LL items, freeing contents and then structure instances
    while(temp!=NULL){
      temp2 = temp->next;
      free(temp->data->url);
      free(temp->data->html);
      free(temp->data);
      free(temp->key);
      free(temp);
      temp = temp2;
    }
    set->head = NULL;
  }

  free(set);
  return;

}

但是我收到了这个错误:

gcc -Wall -pedantic -std=c11 -ggdb   -c -o crawler.o crawler.c
crawler.c: In function ‘setDestroy’:
crawler.c:428:22: warning: dereferencing ‘void *’ pointer
       free(temp->data->url);
                      ^
crawler.c:428:22: error: request for member ‘url’ in something not a structure or union
crawler.c:429:22: warning: dereferencing ‘void *’ pointer
       free(temp->data->html);
                      ^
crawler.c:429:22: error: request for member ‘html’ in something not a structure or union
<builtin>: recipe for target 'crawler.o' failed

关于我可能做错的任何想法?我试图将temp-&gt; data-&gt; url作为字符串转换为无效。

谢谢!

1 个答案:

答案 0 :(得分:2)

正如错误消息所示,temp->datavoid*,因此您无法使用temp->data->htmltemp->data->url。您需要将其强制转换为WebPage*才能访问这些成员。

free(((WebPage*)temp->data)->html);
free(((WebPage*)temp->data)->url);