memory management between functions

Jim Klavetter jjk at jupiter.astro.umd.edu
Mon Apr 29 17:50:36 AEST 1991


A few weeks ago I asked about where to allocate memory, in main()
or in the function.  The general idea I got back was that it
doesn't matter as long as you do it correctly (either place is
ok).

I wanted to make the functions completely autonomous, so this is
what I did (in some c-like metacode)

[includes]
double *subtract(a, b, n)
int n;
double *a, *b;
{
int i;
double *c;

[malloc c array here]

for(i=0; i<n; i++)
	c[i]=a[i]-b[i];
free(c);
return(c);
}

(Again, don't worry about efficiency, this isn't the code, just an
example of the malloc() and free() that is important).

The main program would have the fragments:

[malloc result]

result=subtract(vector1, vector2, n);

...

Conceptually, I like the above.  The problem is that it doesn't
work quite as expected:  when I take a look at the pointer result
(that is &*result, not the result of the pointer) before and after
the function it CAN (but not always does) change.  OK, I know I am
freeing the c array, but the very next thing I do is return it, so
I thought the result pointer would have the information
uncorrupted.

The question:  am I on the right track, or is it completely
impossible the way in which I am doing it?  I am calling subtract
(and many other vector operations) many times so I need to worry
about memory management.

In my first posting, someone offered the advice that the call to
subtract should be:

double *subtract(a, b, n, result)

where result is an "empty" array that will be used to return the
subtracted vector.  I think this would solve the problem, but I am
reluctant to use this idea because of the duplication (as well as
the fortranish look).  Is this NECESSARY duplication that I must
live with?

Thanks to all who helped me out enough last time to get into
trouble this time.

jjk at astro.umd.edu also for Athabasca and Reudi
Jim Klavetter
Astronomy
UMD
College Park, MD  20742



More information about the Comp.lang.c mailing list