gpt4 book ai didi

c - Valgrind 使用 asprintf 报告内存泄漏

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:16 25 4
gpt4 key购买 nike

这是一段基于简单结构在套接字上写入 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);
}

基本上,它首先添加 HTTP 请求行,然后是 header ,最后(如果需要)正文。

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

我使用的 asprintf 对吗?

最佳答案

手册页是这样说的:

The functions asprintf() .... allocate a string...

以后

This pointer should be passed to free(3) to release the allocated storage when it is no longer needed.

每次新调用都会导致新分配。您似乎没有释放先前分配的字符串。

关于c - Valgrind 使用 asprintf 报告内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54781388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com