Jump to content United States-English
HP.com Home Products and Services Support and Drivers Solutions How to Buy
» Contact HP
More options
HP.com home
HP-UX Reference > M

malloc(3C)

HP-UX 11i Version 3: February 2007
» 

Technical documentation

» Feedback
Content starts here

 » Table of Contents

 » Index

NAME

malloc(), alloca(), calloc(), free(), mallinfo(), mallopt(), memorymap(), realloc(), valloc() — main memory allocator

SYNOPSIS

#include <stdlib.h>

void *malloc(size_t size);

void *calloc(size_t nelem, size_t elsize);

void free(void *ptr);

void *realloc(void *ptr, size_t size);

void *valloc(size_t size);

void memorymap(int show_stats); (Obsoleted)

alloca()

#include <alloca.h>

void *alloca(size_t size);

System V Synopsis

#include <malloc.h>

char *malloc(unsigned size);

char *calloc(unsigned nelem, unsigned elsize);

void free(char *ptr);

int mallopt(int cmd, int value);

char *realloc(char *ptr, unsigned size);

struct mallinfo mallinfo(void);

Remarks

The functionality in the old malloc() package has been incorporated into malloc(). The library (/usr/lib/libmalloc.a) corresponding to the -lmalloc linker option is now an empty library on PA-RISC based systems only; it does not exist on Itanium®-based systems. Makefiles that reference this library on PA-RISC based systems will continue to work, but they will not work on Itanium®-based systems.

Obsolescent Interfaces

memorymap() has been deprecated at HP-UX 11i Version 1 and is now obsolete. The mallinfo() function is more useful for malloc statistics.

DESCRIPTION

The functions described here provide a simple, general purpose memory allocation package:

malloc()

Allocates space for a block of at least size bytes, but does not initialize the space.

calloc()

Allocates space for an array of nelem elements, each of size elsize bytes, and initializes the space to zeros. Actual amount of space allocated will be at least nelem * elsize bytes.

realloc()

Changes the size of the block pointed to by ptr to size bytes and returns a pointer to the (possibly moved) block. Existing contents are unchanged up to the lesser of the new and old sizes. If ptr is a NULL pointer, realloc() behaves like malloc() for the specified size. If size is zero and ptr is not a NULL pointer, the object it points to is freed and NULL is returned. realloc() of blocks with special alignments, such as those created by valloc(), is not supported.

valloc()

Allocates space for a block of at least size bytes starting on a boundary aligned to a multiple of the value returned by sysconf (__SC_PAGESIZE). This space is uninitialized.

free()

Deallocates the space pointed to by ptr (a pointer to a block previously allocated by malloc(), realloc(), calloc(), or valloc()) and makes the space available for further allocation. If ptr is a NULL pointer, no action occurs.

mallopt()

Provides for control over the allocation algorithm and other options in the malloc() package. The available values for cmd are:

M_MXFAST

Set maxfast to value. The algorithm allocates all blocks below the size of maxfast in large groups, then doles them out very quickly. The default value for maxfast is zero.

M_NLBLKS

Set numlblks to value. The above mentioned ``large groups'' each contain numlblks blocks. numlblks must be greater than 1. The default value for numlblks is 100.

M_GRAIN

Set grain to value. The sizes of all blocks smaller than maxfast are considered to be rounded up to the nearest multiple of grain. grain must be greater than zero. The default value of grain is the smallest number of bytes that can accommodate alignment of any data type. value is rounded up to a multiple of the default when grain is set.

M_BLOCK

Block all blockable signals in malloc(), realloc(), calloc(), and free(). This option is provided for those who need to write signal handlers that allocate memory. When set, the malloc() routines can be called from within signal handlers (they become re-entrant). Default action is not to block all blockable signals.

NOTE: performance of malloc() will be impacted considerably when the M_BLOCK option is set.

M_UBLOCK

Do not block all blockable signals in malloc(), realloc(), calloc(), and free(). This option cancels signal blocking initiated by the M_BLOCK option.

M_REL_LAST_FBLK

Enable the feature of release last free block to heap. This option is provided for 32-bit applications with one arena. Release of last block happens only when size of the free block is greater than the threshold.

The threshold value is defined as 2 * (arena expansion factor) * 4096 bytes. The feature is disabled if the M_MXFAST value is greater than or equal to threshold value. Default action is not to release last block.

These values are defined in the <malloc.h> header file.

mallopt() can be called repeatedly; but once the first small block is allocated, it is not possible to change the M_MAXFAST, M_NLBLKS, and M_GRAIN values.

mallinfo()

Provides instrumentation describing space usage, but cannot be called until the first small block is allocated. It returns the structure mallinfo:

arena : total space in arena fsmblks : number of bytes in free small blocks fordblks : number of bytes in free ordinary blocks hblks : number of holding blocks hblkhd : number of bytes in holding block headers keepcost : cost of enabling keep option ordblks : number of ordinary blocks smblks : number of small blocks uordblks : number of bytes in ordinary blocks in use usmblks : number of bytes in small blocks in use

The mallinfo structure is defined in the <malloc.h> header file.

Each of the allocation routines returns a pointer to space suitably aligned (after possible pointer coercion) for storage of any type of object.

memorymap()

Displays the contents of the memory allocator for HP-UX 32-bit operating systems only. A list of addresses and block descriptions is written (using printf()) to standard output. If the value of the show_stats parameter is 1, statistics concerning number of blocks and sizes used will also be written. If the value is zero, only the memory map will be written.

The addresses and sizes displayed by memorymap() may not correspond to those requested by an application. The size of a block (as viewed by the allocator) includes header information and padding to properly align the block. The address is also offset by a certain amount to accommodate the header information.

memorymap() has been deprecated at HP-UX 11i Version 1 and is now obsolete.

alloca()

Allocates space from the stack of the caller for a block of at least size bytes, but does not initialize the space. The space is automatically freed when the calling routine exits.

Memory returned by alloca() is not related to memory allocated by other memory allocation functions. Behavior of addresses returned by alloca() as parameters to other memory functions is undefined.

The implementation of this routine is system dependent and its use is discouraged.

RETURN VALUE

Upon successful completion, malloc(), realloc(), calloc(), and valloc() return a pointer to space suitably aligned (after possible pointer coercion) for storage of any type of object. Otherwise, they return a NULL pointer. If realloc() returns a NULL pointer, the memory pointed to by the original pointer is left intact.

mallopt() returns zero for success and nonzero for failure.

DIAGNOSTICS

malloc(), realloc(), calloc(), and valloc() return a NULL pointer if there is no available memory, or if the memory managed by malloc() has been detectably corrupted. This memory may become corrupted if data is stored outside the bounds of a block, or if an invalid pointer (a pointer not generated by malloc(), realloc(), calloc(), or valloc() is passed as an argument to free() or realloc().

If mallopt() is called after any allocation of a small block and cmd is not set to M_BLOCK or M_UBLOCK, or if cmd or value is invalid, nonzero is returned. Otherwise, it returns zero.

ERRORS

ENOMEM

malloc(), realloc(), calloc(), and valloc() set errno to ENOMEM and return a NULL pointer when an out-of-memory condition arises.

EINVAL

malloc(), realloc(), calloc(), and valloc() set errno to EINVAL and return a NULL pointer when the memory being managed by malloc() has been detectably corrupted.

EXTERNAL INFLUENCES

For PA-RISC based systems, the performance of the malloc() family of APIs can be tuned via the environment variables _M_ARENA_OPTS, _M_SBA_OPTS, and _M_CACHE_OPTS.

For Itanium®-based systems, in addition to _M_ARENA_OPTS, _M_SBA_OPTS, and _M_CACHE_OPTS, three global variables can be used for performance tuning: __hp_malloc_maxfast, __hp_malloc_num_smallblocks, and __hp_malloc_grain.

For threaded applications, malloc() uses multiple arenas. Memory requests from different threads are handled by different arenas. _M_ARENA_OPTS can be used to adjust the number of arenas and how many pages each time an arena expands itself (the expansion factor), assuming that the page size is 4096 bytes. In general, the more threads in an application, the more arenas should be used for better performance. The number of arenas can be from 1 to 64 for threaded applications.

For non-threaded applications, only one arena is used. If the environment variable is not set, or the number of arenas is set to be out of the range, the default number of 8 will be used. The expansion factor is from 1 to 4096, default value is 32. Again, if the factor is out of the range, the default value will be used.

Here is an example of how to use _M_ARENA_OPTS,

$ export _M_ARENA_OPTS = 16:8

This means that the number of arenas is 16, and the expansion size is 8*4096 bytes. In general, the more arenas you use, the smaller the expansion factor should be, and vice versa.

_M_SBA_OPTS is used to turn on the small block allocator, and to set up parameters for the small block allocator, namely, maxfast, grain, and numlblks. Applications with small block allocator turned on usually run faster than with it turned off. Small block allocator can be turned on through mallopt(); however, it is not early enough for C++/Java applications. The environment variable turns it on before the application starts. The mallopt() call can still be used the same way. If the environment variable is set, and no small block allocator has been used, the subsequent mallopt() calls can still overwrite whatever is set through _M_SBA_OPTS. If the environment variable is set, and small block allocator has been used, then mallopt() will have no effect.

To use this environment variable,

$ export _M_SBA_OPTS = 512:100:16

This means that the maxfast size is 512, the number of small blocks is 100, and the grain size is 16. You have to supply all 3 values, and in that order. If not, the default values will be used instead.

Three new global variables, __hp_malloc_maxfast, __hp_malloc_num_smallblocks, and __hp_malloc_grain are introduced for Itanium-based systems to over-ride the _M_SBA_OPTS environment option. When these three variables are initialized within an application, _M_SBA_OPTS has no effect. This way, a finely tuned application can lock in performance across different user environments. However, as _M_ARENA_OPTS, a subsequent call to mallopt() before any block of memory was allocated will change the malloc() behavior. By default, these three variables will be initialized to zero at start up. It is the same as setting them to

extern int __hp_malloc_maxfast=512; extern int __hp_malloc_num_smallblocks=100; extern int __hp_malloc_grain=16;

By default, SBA (Small Block Allocation) is turned on for Itanium-based systems. This may contribute to better application performance. A user can set

extern int __hp_malloc_maxfast=-1;

This will turn off SBA.

For all other possible values, please refer to mallopt().

_M_CACHE_OPTS is used to turn on the thread local cache. Turning this option on sets up a private cache for each thread to which access is effectively non-threaded, so there is less contention on the arenas. For some multi-threaded applications this can give a significant performance improvement.

The thread local cache saves blocks of sizes that have previously been used, and thus may be requested again. The size of the cache is configurable. The cache is organized in buckets of sizes that are powers of two; that is, there is a bucket for all blocks in the size range 64-127 bytes, another for 128-255 bytes, and so on.

Thread Local Cache can be tuned by setting the _M_CACHE_OPTS environment variable as follows:

_M_CACHE_OPTS=bucket_size:buckets:retirement_age: max_cache_misses:num_global_slots

The values must be supplied in the exact order indicated. The first three parameters are mandatory, and the last two are optional.

bucket_size denotes the number of pointers cached per bucket. If bucket_size is 0, then thread local cache is disabled. The maximum value for bucket_size is 32768.

buckets is an indication of the number of buckets. The maximum block size that will be cached is 2^buckets. buckets can range between 8 and 32.

retirement_age is an indication in minutes of after how long blocks in an unused cache will be released to the arena. retirement_age is only a hint, so caches may or may not be retired after the specified time period. If retirement_age is 0, retirement is disabled. The maximum value for retirement_age is 1440 (that is, 24 hours).

max_cache_misses enables cached blocks to be exchanged among threads. A thread that heavily allocates blocks of a certain size is soon bound to run out of blocks in its private cache. The exchange allows the thread to borrow blocks from a global pool if available. This may be more efficient than going back to the arena. max_cache_misses is a hint to the caching algorithm indicating a particular number of cache misses after which it will search the global pool for appropriate sized blocks. The algorithm also releases unused cache blocks to the global pool. If max_cache_misses is 0 or not set, cache exchange is turned off.

num_global_slots is an indication of the size of the global cache pool. This parameter is valid only if max_cache_misses is turned on. The default value for num_global_slots is 8.

The maximum number of blocks that will be cached for each thread is bucket_size * buckets.

Here are examples of how to use _M_CACHE_OPTS,

$ export _M_CACHE_OPTS = 1024:32:20:4:8

This means that bucket_size is 1024, buckets is 32, retirement_age is 20 minutes, max_cache_misses is 4, and num_global_slots is 8.

$ export _M_CACHE_OPTS = 1024:32:20

This is a valid configuration where the global pool is not activated.

_M_ARENA_OPTS and _M_CACHE_OPTS have no effect on non-threaded applications, while _M_SBA_OPTS has.

NOTE: Modifying these variables increases the chances of surfacing existing user memory defects such as buffer overrun.

WARNINGS

malloc() functions use brk() and sbrk() (see brk(2)) to increase the address space of a process. Therefore, an application program that uses brk() or sbrk() must not use them to decrease the address space, because this confuses the malloc() functions.

free() and realloc() do not check their pointer argument for validity.

The following actions are considered bad programming practices and should not be done. The results are unpredictable, probably undesirable and not supported. Examples of undesirable results are loss of data, memory fault, bus error or infinite loop.

  • Attempting to free() or realloc() a pointer not generated as the result of a call to malloc(), realloc(), calloc(), or valloc().

  • Reading or writing data outside the boundaries of an allocated block.

  • Attempting to realloc() an aligned block such as the result of valloc().

The following actions are strongly discouraged and may be unsupported in a future version of malloc():

  • Attempting to free() the same block twice.

  • Depending on unmodified contents of a block after it has been freed.

  • Attempting to realloc() a block after it is freed.

Undocumented features of earlier memory allocators have not been duplicated. Applications which used any of the above bad programming practices or discouraged practices are not guaranteed to continue functioning at future releases.

Compatibility

The only external difference between the old malloc() allocator and the malloc() allocator is that the old allocator would return a NULL pointer for a request of zero bytes. The malloc() allocator returns a valid memory address. This is not a concern for most applications.

By default, SBA (Small Block Allocation) is turned on for Itanium-based systems and is turned off for PA-RISC systems. This was due to performance concerns. Please refer to the EXTERNAL INFLUENCES section of this manpage for details.

STANDARDS CONFORMANCE

malloc(): AES, SVID2, SVID3, XPG2, XPG3, XPG4, FIPS 151-2, POSIX.1, ANSI C

calloc(): AES, SVID2, SVID3, XPG2, XPG3, XPG4, FIPS 151-2, POSIX.1, ANSI C

free(): AES, SVID2, SVID3, XPG2, XPG3, XPG4, FIPS 151-2, POSIX.1, ANSI C

mallinfo(): SVID2, XPG2

mallopt(): SVID2, SVID3, XPG2

realloc(): AES, SVID2, SVID3, XPG2, XPG3, XPG4, FIPS 151-2, POSIX.1, ANSI C

Printable version
Privacy statement Using this site means you accept its terms Feedback to webmaster
© 1983-2007 Hewlett-Packard Development Company, L.P.