MALLOC(3C) UNIX Programmer's Manual MALLOC(3C) NAME malloc, free, realloc, calloc - main memory allocator SYNOPSIS char *malloc (size) unsigned size; free (ptr) char *ptr; char *realloc (ptr, size) char *ptr; unsigned size; char *calloc (nelem, elsize) unsigned nelem, elsize; HP-UX COMPATIBILITY Level: HP-UX/RUN ONLY Origin: System III DESCRIPTION _M_a_l_l_o_c and _f_r_e_e provide a simple general-purpose memory allocation package. _M_a_l_l_o_c returns a pointer to a block of at least _s_i_z_e bytes beginning on a word boundary. Note that, for requests for zero bytes (_s_i_z_e = 0), _m_a_l_l_o_c still returns a valid pointer. The allocated block of memory is not initialized in any way. The argument to _f_r_e_e is a pointer to a block previously allocated by _m_a_l_l_o_c; this space is made available for further allocation, but its contents are left undisturbed. Needless to say, serious disorder will result if the space assigned by _m_a_l_l_o_c is overrun or if some random number is handed to _f_r_e_e. _M_a_l_l_o_c allocates the first big enough contiguous reach of free space found in a circular search from the last block allocated or freed, coalescing adjacent free blocks as it searches. It calls _s_b_r_k (see _b_r_k(2)) to get more memory from the system when there is no suitable space already free. _R_e_a_l_l_o_c changes the size of the block pointed to by _p_t_r to _s_i_z_e bytes and returns a pointer to the (possibly moved) block. The contents will be unchanged up to the lesser of the new and old sizes. _R_e_a_l_l_o_c also works if _p_t_r points to a block freed since the last call of _m_a_l_l_o_c, _r_e_a_l_l_o_c, or _c_a_l_l_o_c; thus sequences of _f_r_e_e, _m_a_l_l_o_c and _r_e_a_l_l_o_c can exploit the search strategy of _m_a_l_l_o_c to do storage compaction. _C_a_l_l_o_c allocates space for an array of _n_e_l_e_m elements of size _e_l_s_i_z_e. The space is initialized to zeros. Each of the allocation routines returns a pointer to space suitably aligned (after possible pointer coercion) for storage of any type of object. DIAGNOSTICS _M_a_l_l_o_c, _r_e_a_l_l_o_c and _c_a_l_l_o_c return a null pointer (0) if there is no available memory or if the arena has been detectably corrupted by storing outside the bounds of a block. When _r_e_a_l_l_o_c returns 0, the block pointed to by _p_t_r may be destroyed. BUGS _F_r_e_e does not check its pointer argument for validity. When passed a null pointer (value 0), it causes a memory fault.