Finding size of a malloc()ed block (was: Finding names of open files)

Neil Hunt hunt at spar.SPAR.SLB.COM
Sat Feb 6 04:16:29 AEST 1988


On malloc on V6, V7 and BSD:

On several UNIXs, malloc returns pretty much exactly the space you ask for;
however, it does call sbrk to obtain memory from the system
in larger chunks, which it maintains itself.

The size parameter is often stored in an integer word immediately
preceeding the returned block; hence:

#define Malloc_size(p)	(*((int *)p) - 1)

For the person who wants to save items incrementally: don't use
malloc and realloc for each item - it's too expensive.
Use a linked list. But don't malloc each block separately:

#define N_ALLOC 1000

struct item *
new_item()
{
	static struct item *free_list = NULL;
	struct item *p;

	/*
	 * If the free list is empty..
	 */
	if(free_list == NULL)
	{
		/*
		 * Allocate N_ALLOC items.
		 */
		if((free_list = (struct item *)calloc(
		  sizeof(struct item), N_ALLOC)) == NULL)
			prexit("Out of memory\n");

		/*
		 * Link them together
		 */
		for(p = free_list; p < free_list + N_ALLOC - 1; p++)
			p->next = p + 1;
	}

	/*
	 * Obtain the next free item.
	 */
	p = free_list;
	free_list = p->next;
	p->next = NULL;

	/*
	 * Return it.
	 */
	return p;
}

As an alternative to linking the new free items into a linked list
in the static free_list, just use a counter of remaining free items.

If you are freeing your items as well as allocating them,
then move the free list to a file static variable and write a free_item
function which returns used items to the free list.

Neil/.



More information about the Comp.unix.wizards mailing list