Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid memory leak during development in c

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.

like image 774
john Avatar asked Nov 29 '22 03:11

john


2 Answers

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 malloced".

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 frees all memory it owns when it itself is disposed of.

like image 131
Employed Russian Avatar answered Dec 04 '22 11:12

Employed Russian


Use variables on stack if possible rather than using memory from heap.

Try to avoid common mistakes, a few pointers:

  1. Make sure to call free() when you use malloc() or calloc().
  2. Don't reassign pointer which points to allocated memory location without free()ing it first i.e. don't lose the reference.
  3. Be careful when using realloc(). Do not use the same pointer for input & output parameters.

Avoid common mistakes made using strings, a few pointers:

  1. Make sure there is memory for terminating NUL character.
  2. Make sure string is 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!

like image 27
another.anon.coward Avatar answered Dec 04 '22 11:12

another.anon.coward