Sujet : Re: valgrind leak I can't find
De : mark (at) *nospam* qtrac.eu (Mark Summerfield)
Groupes : comp.lang.cDate : 22. Aug 2024, 18:44:43
Autres entêtes
Message-ID : <oKScnQbmXbeW5Fr7nZ2dnZfqn_GdnZ2d@brightview.co.uk>
References : 1
User-Agent : Pan/0.149 (Bellevue; 4c157ba)
Thank you to all who replied.
TL;DR The problem turned out to be a double-free because I had two owning
collections with the same strings. I've now made VecStr and SetStr able to
be owning or nonowning and this valgrind leak has gone.
- I don't want to post the code since it is just for me relearning C.
(I'm creating a tiny collections lib: Vec (of void*), VecStr, VecInt,
SetInt, SetStr.)
- The reason I special cased when index == vec->_size is that I did a
needless premature "optimization": I no longer do this.
- I use underscores for some struct fields. For the collections I provide
functions for their APIs but of course the fields are not private so I use
the underscore in a Python-like way to remind myself they are "private".
- Yes, I free as needed:
typedef struct {
int _size;
int _cap;
char** _values;
bool _owns; // new
} VecStr;
void vec_str_free(VecStr* vec) {
assert_notnull(vec);
vec_str_clear(vec);
free(vec->_values);
vec->_values = NULL;
vec->_cap = 0;
}
void vec_str_clear(VecStr* vec) {
assert_notnull(vec);
if (vec->_owns)
for (int i = 0; i < vec->_size; ++i)
free(vec->_values[i]);
vec->_size = 0;
}