[vox-tech] Assistance With C Program

Peter Jay Salzman vox-tech@lists.lugod.org
Tue, 18 Nov 2003 17:02:06 -0800


hi dan,

On Tue 18 Nov 03,  4:40 PM, Daniel Hurt <dwhurt@ucdavis.edu> said:
> 
> Specifically:  Finding possible memory leaks and when it is appropriate to 
> use the free() functions. Next, I am not too terribly sure on how to use a 
> debugger to track down the leak.  Finally, just discussing programming 
> style with someone who knows C to look at it and critique the code.  The 
> code itself works, it just takes an exceedingly long time and every so 
> often I am running into problems with the size of the program.  I do not 
> need help with the physics behind what is going on because the code 
> actually generates good results. I am just trying to analyze larger 
> systems that should be well within the limits and encountering problems.
 
if i can guess at what your research is, you don't need to use dynamic
memory for your spin lattice if you use c99.  you can declare arrays
with non-constants, so you can do something like this:

./montecarlo --latticesize=50

and you don't need to allocate the array dynamically.


but to answer your question, it's always appropriate to use free()
whenever you use malloc() and friends (except for dynamic memory
allocated from the stack, like alloca()).  if you don't, the memory is
unavailable for the duration of your application, but will be returned
when your program exits.  if you're doing monte carlo on small lattices,
a memory leak is really not a big deal since you only allocate the array
once.  it's just unaesthetic.


to answer your question about how to find memory leaks: there's lots and
lots and lots of ways.  some easy, and some hard.  look at

   info libc

and do a search on MALLOC_CHECK.  you'll be taken to a node that has a
few ways to catch dynamic memory problems.  the simplest method is the
MALLOC_CHECK_ method itself (note the terminating underscore).

basically, you'll want to set an environment variable named
MALLOC_CHECK_ to a 0 (to ignore problems), a 1 (to warn about problems)
or a 2 (to dump core when a problem is encountered) or a 3 (to both warn
and dump core when a problem is encountered).

note that "3" is undocumented.   you can invoke it like so:

   $ MALLOC_CHECK_=3 ./myprogram

i can give you further guidance if you need it.


there are meny other ways.  see "man efence" for example.  electric
fence is another tool to debug dyanmic memory problems.  each tool has
its strengths and weaknesses.  

for instance, MALLOC_CHECK_ doesn't work with the concept of
"boundaries" while electric fence does.  this means that efence can
catch certain problems that MALLOC_CHECK_ can't.  for instance, i
believe pure memory leaks will not be detected by MALLOC_CHECK_, while
things like double frees and writing to freed memory will.

hth,
pete

-- 
GPG Instructions: http://www.dirac.org/linux/gpg
GPG Fingerprint: B9F1 6CF3 47C4 7CD8 D33E 70A9 A3B9 1945 67EA 951D