typedef struct {
int **a;
int **b;
int **c;
int i;
} test_t;
test_t *create(int i) {
test_t *test = malloc(i * sizeof(test_t));
test->i = i;
test->c = malloc(i * sizeof(int *));
for (int j = 0; j < i; ++j) {
test->c[j] = malloc(sizeof(int *));
}
test->a = malloc(sizeof(int *));
test->a = &(test->c[0]);
test->b = malloc(sizeof(int *));
test->b = &(test->c[0]);
return test;
}
void delete(test_t *test) {
free(test->a);
free(test->b);
for (int i = 0; i < test->i; ++i)
free(test->c[i]);
free(test->c);
free(test);
}
int main() {
test_t *test;
test = create(3);
delete(test);
return 0;
}
What's wrong with this code?
When I run Valgrind, I get 5 errors and some memory leaks.
I don't see any memory leak, do you?
I get errors like:
Invalid free() / delete / delete[] / realloc()
Address 0x4a380e0 is 0 bytes inside a block of size 24 free'd
Block was alloc'd at
Invalid read of size 8
Could anybody help me with that, please?
P.S. The code works fine, but it has memory leaks, so it doesn't.
test->a = malloc(sizeof(int *)); test->a = &(test->c[0]);What do you think that does? The second expression overwrites themallocresult from the first. That results in a memory leak. And when you freetest->ait will be somewhere insidec. Which is exactly what valgrind tells you. - kaylumtest->a = some-addressoverwritestest->aaddress? When I try toprintfthat, it is not overwritten. That's weird. I'd like to store an address of a first item in array totest->aandtest->b. - John Doe