Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find memory leaks in a C program

I am trying to complete a college assignment, and the marking criteria specifies 5% for memory management - specifically for having no memory leaks.

As I understand it, memory leaks in simple C programs, are only caused by pointers which have become abandoned by the program - ie, malloc/calloc/etc calls which are never have a corresponding free.

My question is in 3 parts:

  1. Whats the simplest way on Solaris and OSX to 'prove' that you haven't leaked any memory?
  2. Does XCode have any tools to help determine memory leaks?
  3. Does the operating system release all previously allocated memory within a c program once the process ends?
like image 906
Ash Avatar asked Dec 28 '22 20:12

Ash


2 Answers

Valgrind is your friend.

like image 117
Alex Reynolds Avatar answered Dec 30 '22 09:12

Alex Reynolds


  1. For every malloc(), you need to ensure that you have exactly one free().
  2. I haven't worked with XCode, but this forum entry may help.
  3. Yes. It's still poor form to let your running program 'leak,' however.

In general, it's a good idea to learn how to avoid leaks without using tools like a memory debugger (early on) -- especially for your simple programs. It's painful, however: when it comes to building anything non-trivial you'll want to start learning how to use the more advanced debugging tools (like Valgrind, as Alex Reynolds suggested in another answer.)

like image 31
Joe Avatar answered Dec 30 '22 08:12

Joe