我一直在争论一个似乎是realloc与valgrind不能很好合作的奇怪案例.似乎我要么分配太多,要么使用realloc不正确.我认真对待valgrind错误,这样的错误让我深感担忧.
最小的工作示例:
#include <stdlib.h>
typedef struct test {
size_t n;
size_t r;
int **ptrs;
} test;
test *new_test() {
test *t = malloc(sizeof(test));
t->n = 0; //number of elements
t->r = 1; //reserve
t->ptrs = calloc(t->r, sizeof(*(t->ptrs))); //calloc inits so we don't have to
return t;
}
void push_back_test(test *t, int *ptr) {
if (t->n == t->r) {
t->r <<= 1;
int **temp_ptr = realloc(t->ptrs, sizeof(t->ptrs) * t->r);
if (temp_ptr) {
t->ptrs = temp_ptr;
} else …Run Code Online (Sandbox Code Playgroud)