Valgrind用asprintf报告内存泄漏

Ark*_*kon 1 c linux valgrind

这是一段基于简单结构在套接字上写入HTTP响应的代码

void write_response(request *req, response *resp, int socket) {
  char *raw_resp;
  int bytes = 0;

  asprintf(&raw_resp, "HTTP/1.1 %d %s\r\n", resp->code, resp->reason_phrase);

  bytes += strlen(raw_resp);
  for (int i = 0; i < resp->header_count; i++) {
    asprintf(&raw_resp, "%s%s", raw_resp, resp->headers[i]);
    bytes += strlen(resp->headers[i]);
  }

  if (resp->content != NULL) {
    asprintf(&raw_resp, "%s\r\n", raw_resp);
    raw_resp = realloc(raw_resp, bytes + 2 + resp->content->size);
    memcpy(&raw_resp[strlen(raw_resp)], resp->content->data,
           resp->content->size);
    bytes += (resp->content->size + 2);
  }
  write(socket, raw_resp, bytes);
  free(raw_resp);
}
Run Code Online (Sandbox Code Playgroud)

基本上,它首先添加HTTP请求行,然后添加标题,最后添加主体.

但是,valgrind报告了前2个asprintf上的a Invalid free() / delete / delete[] / realloc()18 bytes in 1 blocks are definitely lost in loss record 2 of 4(内存泄漏),但奇怪的是不是第3个.

我使用asprintf吗?

Igo*_*.K. 5

这是手册页所说的内容:

函数asprintf()....分配一个字符串......

然后

应该将此指针传递给free(3)以在不再需要时释放已分配的存储.

每次新呼叫都会导致新的分配.您似乎没有释放以前分配的字符串.