Iam programming in C. I want to know what practice we should follow to avoid Memory Leaks at the time of development itself. Please mention the precautions to be taken specially while dealing with strings and dynamic memory allocation.
I don't agree with down-votes on this question. I think it's a real question, and quite deep.
On the surface, the answer is "call free
on any memory you malloc
ed".
But the real answer is that your design should include a clear ownership model. The only way to avoid memory leaks and access to dangling memory is to always know, for every piece of dynamically allocated memory, what object owns that memory (and is responsible for disposing of it).
If you don't have such a clear ownership model, you will forever hunt memory leaks and use-after-free bugs (this also applies to C++). Use of garbage collector would allow you to plaster over these problems, at the cost of significant CPU cycles.
If you do have a clear ownership model, these problems generally just disappear: the owner free
s all memory it owns when it itself is disposed of.
Use variables on stack if possible rather than using memory from heap.
Try to avoid common mistakes, a few pointers:
free()
when you use malloc()
or calloc()
. free()
ing it first i.e. don't lose the reference. realloc()
. Do not use the same pointer for input & output parameters. Avoid common mistakes made using strings, a few pointers:
NUL
character. NUL
terminated in all your use cases (even when used in functions like strncpy()
etc.)Learn to use a debugger (gdb)
Learn to use static analysis tools. Tools like splint, valgrind, clang can be installed on you linux system from your distro's package repository.
Few useful links:
c-faq - Arrays & Pointers
c-faq - Memory allocation
Secure C Coding - Memory Management
SO Question related to avoiding memory leak in C/C++
yolinux tutorial
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With