Path: utzoo!mnetor!uunet!seismo!sundc!pitstop!sun!decwrl!spar!hunt From: hunt@spar.SPAR.SLB.COM (Neil Hunt) Newsgroups: comp.unix.wizards Subject: Re: Finding size of a malloc()ed block (was: Finding names of open files) Message-ID: <653@spar.SPAR.SLB.COM> Date: 5 Feb 88 18:16:29 GMT References: <2346@mandrill.CWRU.Edu> <339@tandem.UUCP> <7124@ncoast.UUCP> <1427@mips.mips.COM> <461@minya.UUCP> <16713@watmath.waterloo.edu> Reply-To: hunt@spar.UUCP (Neil Hunt) Organization: SPAR - Schlumberger Palo Alto Research Lines: 63 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/.