gpt4 book ai didi

c - realloc - 内存泄漏

转载 作者:太空宇宙 更新时间:2023-11-04 04:06:34 28 4
gpt4 key购买 nike

我有一些 C 代码:

typedef struct {
size_t len;
size_t alloclen;
char *buf;
} str;

void strnappnd(str **s, const char *buf, size_t n) {

if ((*s)->len + n >= (*s)->alloclen) {
size_t nalloclen = (*s)->len + n + 1;
void *tmp = realloc((*s)->buf, nalloclen);
if (!tmp) {
printf("failure");
exit(-1);
}
(*s)->buf = tmp;
(*s)->alloclen = nalloclen;
}
memccpy((*s)->buf + (*s)->len, buf, '\0', n);
(*s)->len += n;
(*s)->buf[(*s)->len] = '\0';
}

void strfree(str **s) {
free((*s)->buf);
free(*s);
*s = NULL;
}

显然,strnappnd 在 realloc 行泄漏。为什么?

最佳答案

考虑:

void f() {
str *s = (str *)malloc(sizeof(str));
s->len = 5;
s->alloclen = 5;
s->buf = strdup("Hello");
strnappend(&s, " World!", 7);
free(s); /* courtesy of Eric */
}

如果你有类似的东西,由 realloc() 分配的内存将在 f() 剩余时泄漏。

关于c - realloc - 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5339282/

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