scope of malloc

Conor P. Cahill cpcahil at virtech.uucp
Thu Nov 8 00:49:42 AEST 1990


In article <1791 at sirius.ucs.adelaide.edu.au> mferrare at adelphi.ua.oz.au (Mark Ferraretto) writes:
>	When malloc is called in a function and the scope of the pointer is
>only that function is the memory deallocated when the pointer is (ie on exit
>of the function?) deallocated?

The data area pointed to by the value returned by malloc is allocated and
available until you free it or the program exits.

>I am calling several functions that involve a lot of
>dynamic memory allocation most of which is only relevant to the scope of the
>function where the memory is allocated.  These functions get called repeatedly.
>So do I need to fill these functions to include free() calls with at the end
>of each function?

Instead you could do something like:

	func() {
		static char *  pointer = NULL;

		if( pointer == NULL )
			pointer = malloc()...

If the pointer changes size:

		if( pointer == NULL )
			pointer = malloc(...
		else if ( new_size > old_size )
			pointer = realloc(...

If you just want the pointer to be around during the function, you can
use alloca() which allocates the data on your stack.  This function is 
usually hidden in the libPWB.a library.

-- 
Conor P. Cahill            (703)430-9247        Virtual Technologies, Inc.,
uunet!virtech!cpcahil                           46030 Manekin Plaza, Suite 160
                                                Sterling, VA 22170 



More information about the Comp.lang.c mailing list