我有一些 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/