C Memory leak, or maybe not?

My advice is DON'T use C++. Avoid it whenever possible.
Completely agree 6502 . Sorry, eternal noob, most of what you say makes solid sense, but not this time 😂
Well, I guess if you used C++ and only used smart pointers, that might not be too bad. Just don't use all the rest of the C++ gorp.
 
The question is not for embedded software. And memory leaks are not related to fragmentation.
Well, fair enough, fragmentation was probably the wrong word. Let's just say "your heap will slowly grow". I guess we haven't isolated the bug yet though. We don't know for certain where the memory leak is occurring, I was just guessing its a heap leak from the repeated free then malloc shown in the listing. Then again, no-one has answered my question yet, which is why does the hashtable need to use dynamic memory at all? But maybe the leak is happening somewhere else, it's not like we've seen all the code, so who knows.

PS I think the key is that it's a long-running process. It doesn't really matter whether it's embedded, a userland program, or whatever. If the thing stays running for 6 months and it's continually doing free then malloc as the OP showed in the listing, then you're going to see small leaks growing. If you're really, really lucky, the heap manager will continually free and then alloc exactly the same block, but you will have to be really lucky.
 
C language requires some skills and discipline. If you have them, memory leaks will occur rarely. If somebody needs smart pointers and cannot work without them, then is a good idea to choose another language - Rust, Go, C#, etc.

I know there are automated tools to catch leaks, but a simple self-made solution is to redirect `malloc` and `free` to your functions or macros, keep list of allocated blocks with corresponding `malloc` call line numbers and time and remove entries when `free` is called. Then you can print a list of blocks still allocated and find reason for leaks. Sounds complex? If somebody wants to use C, this is a little exercise.
 
Back
Top