/* * malloc * This is exactly the same as the alloc() function provided in BDS C. * It conforms very closely to the function in the Version 7 U**X C * Library. * Last Edit 7/1/83 */ char * malloc(nbytes) unsigned nbytes; { struct _header *p, *q, *cp; int nunits; nunits = 1 + (nbytes + (sizeof (_Base) - 1)) / sizeof (_Base); if ((q = _allocp) == NULL) { _Base._ptr = _allocp = q = &_Base; _Base._size = 0; } for (p = q -> _ptr; ; q = p, p = p -> _ptr) { if (p -> _size >= nunits) { if (p -> _size == nunits) q -> _ptr = p -> _ptr; else { p -> _size -= nunits; p += p -> _size; p -> _size = nunits; } _allocp = q; return p + 1; } if (p == _allocp) { if ((cp = sbrk(nunits * sizeof (_Base))) == ERROR) return NULL; cp -> _size = nunits; free(cp+1); /* remember: pointer arithmetic! */ p = _allocp; } } } /* * calloc * Allocate space with zero fill for `n' items of size 'size'. Conforms * closely to the function in the Version 7 U**X Standard Library. * Last Edit 7/1/83 */ char * calloc(n,size) int n, size; { char *valp; int i; i = n*size; if ((valp=malloc(i)) == NULL) return NULL; while (--i >= 0) valp[i] = '\0'; return(valp); } /* * realloc * This function increases the size of a contiguous space previously * allocated using calloc() or malloc(). It conforms exactly to the * function in the Version 7 U**X Library. Note that the old space * should be freed just prior to calling realloc(). * Last Edit 7/1/83 */ char * realloc(ptr, size) char *ptr; unsigned size; { char *nptr; if ((nptr = calloc(size,1)) == NULL) return 0; movmem(ptr, nptr, size); return nptr; } /* * free * This function is essentially the same as the function in * the BDS C Standard Library. * Last Edit 7/1/83 */ free(ap) struct _header *ap; { struct _header *p, *q; p = ap - 1; for (q = _allocp; !(p > q && p < q->_ptr); q = q->_ptr) if (q >= q->_ptr && (p > q || p < q->_ptr)) break; if (p + p->_size == q->_ptr) { p->_size += q->_ptr->_size; p->_ptr = q->_ptr->_ptr; } else p->_ptr = q->_ptr; if (q + q->_size == p) { q->_size += p->_size; q->_ptr = p->_ptr; } else q->_ptr = p; _allocp = q; }