简体   繁体   中英

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 ac program once the process ends?

Valgrind是你的朋友。

  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.)

Answer for Mac OS and an example to be avoided (saved you half an hour).


Mac OS doesn't come with Valgrind or dmalloc. Moreover, Valgrind has some compatibility issues when trying to get it installed in Sierra.

There is utility called "leaks", which I get it running by this:

leaks -atExit --/Contents/Developer/usr/lib/libLeaksAtExit.dylib ./a.out

Unfortunately, this doesn't report obvious memory leaks ... Maybe I am using it wrong, but I was just searching for an easy way to check that my C program free'd its memory as it should.

If you have time, then maybe read and use Using OSX Leaks for C Programs on the Command Line?

Resources:

  1. Finding Memory Leaks
  2. Using the "leaks" command on a C/C++ executable

PS: Maybe if used with "iprofiler", then it might be useful, but I didn't had it installed.

还有dmalloc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM