valloc(3)

Chris Torek chris at mimsy.umd.edu
Sat Dec 16 07:16:02 AEST 1989


In article <1509 at utkcs2.cs.utk.edu> battle at alphard.cs.utk.edu
(David Battle) writes:
>Is it safe to free memory allocated with valloc(3) using free(3) on
>an Ultrix system?  I ask because valloc adds some to the pointer
>returned by malloc in order to allign the returned address.

I am not sure about Ultrix specifically (the answer may well depend
on which release of Ultrix is used), but in general, no, it is not
safe.  Valloc is a botch because there is no vfree.

The following is equivalent to valloc on VAXen and Suns but provides
a way to free the memory allocated:

	char *malloc();

	char *get_page_aligned_memory(nbytes, base)
		unsigned nbytes;
		char **base;
	{
		register char *p;
		static int pageround;

		/* this assumes getpagesize() returns a power of 2 */
		if (pageround == 0)
			pageround = getpagesize() - 1;
		p = malloc((nbytes + pageround) & ~pageround);
		if (base != NULL)
			*base = p;
		if (p == NULL)
			return (NULL);
		return ((char *)(((long)p + pageround) & ~pageround));
	}

		usage:
	...
		char *mem, *base;
		mem = get_page_aligned_memory((unsigned)1024, &base);
		if (mem == NULL) ... error ...
		...
		free(base);

Some versions of malloc `happen' to return page-aligned memory already.
If you wish to trust it, you can change get_page_aligned_memory to

	char *get_page_aligned_memory(unsigned nbytes, char **base) {
		return (*base = malloc(nbytes));
	}

or

	#define get_page_aligned_memory(nbytes, base) \
		(*(base) = malloc(nbytes))

and everything will continue to work.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.unix.wizards mailing list