
simple malloc question in functions
Quote:
>hello,
>I have a question regarding malloc. I was under the assumption that
>variables declared in functions were local to that function and is freed
>when the function is exited.
Automatic variables are created when the *block* they are defined in is
entered and they are destroyed when that block is exited. For example:
void foo(int x) /* Function parameters are created on entry to the function
and destroyend when it exits */
{
static int t; /* static variables always exist throughout the lifetime
of the program */
int y; /* An automatic variable at the outermost block level in
a function in effect is created when then function is
entered and destroyed when the function returns */
{
int z; /* An automatic variable in an inner block is created
when the *block* is entered and destroyed when the
block is left (execution falls out the bottom, the
block is jumped out of, or a return is executed within
the block.
}
Quote:
}
>I was writing a program which declared a
>variable in a function and allocated space using malloc(). After about
>letting the program run for a few minutes, i discovered that the program
>started swapping to the hard drive for virtual memory (I use djgpp). The
>problem was fixed when I called free() before exiting the function. Does
>the memory still persist when allocated with malloc() (or similar
>dynamically allocating function) even when it exits the function? Thank
>you for any help.
malloc'd memory persists until you free it. For example in:
void *bar(void)
{
void *p =- malloc(100);
return p;
Quote:
}
p itself is a pointer variable, it is automatic and is destroyed when the
function returns. However what it *points to* is an object allocated by
malloc() and that is not automatic. It remains in existence until it is
freed. The pointer value returned by bar() can be used by the caller to
reference the malloc'd object.
--
-----------------------------------------
-----------------------------------------