📄 memory.texi
字号:
memory space is available to make the block bigger. When this happens,the original block is untouched; it has not been modified or relocated.In most cases it makes no difference what happens to the original blockwhen @code{realloc} fails, because the application program cannot continuewhen it is out of memory, and the only thing to do is to give a fatal errormessage. Often it is convenient to write and use a subroutine,conventionally called @code{xrealloc}, that takes care of the error messageas @code{xmalloc} does for @code{malloc}:@smallexamplevoid *xrealloc (void *ptr, size_t size)@{ register void *value = realloc (ptr, size); if (value == 0) fatal ("Virtual memory exhausted"); return value;@}@end smallexampleYou can also use @code{realloc} to make a block smaller. The reason youwould do this is to avoid tying up a lot of memory space when only a littleis needed. Making a block smaller sometimes necessitates copying it, so itcan fail if no other space is available.If the new size you specify is the same as the old size, @code{realloc}is guaranteed to change nothing and return the same address that you gave.@node Allocating Cleared Space@subsection Allocating Cleared SpaceThe function @code{calloc} allocates memory and clears it to zero. Itis declared in @file{stdlib.h}.@pindex stdlib.h@comment malloc.h stdlib.h@comment ANSI@deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})This function allocates a block long enough to contain a vector of@var{count} elements, each of size @var{eltsize}. Its contents arecleared to zero before @code{calloc} returns.@end deftypefunYou could define @code{calloc} as follows:@smallexamplevoid *calloc (size_t count, size_t eltsize)@{ size_t size = count * eltsize; void *value = malloc (size); if (value != 0) memset (value, 0, size); return value;@}@end smallexampleWe rarely use @code{calloc} today, because it is equivalent to such asimple combination of other features that are more often used. It is ahistorical holdover that is not quite obsolete.@node Efficiency and Malloc@subsection Efficiency Considerations for @code{malloc}@cindex efficiency and @code{malloc}To make the best use of @code{malloc}, it helps to know that the GNUversion of @code{malloc} always dispenses small amounts of memory inblocks whose sizes are powers of two. It keeps separate pools for eachpower of two. This holds for sizes up to a page size. Therefore, ifyou are free to choose the size of a small block in order to make@code{malloc} more efficient, make it a power of two.@c !!! xref getpagesizeOnce a page is split up for a particular block size, it can't be reusedfor another size unless all the blocks in it are freed. In manyprograms, this is unlikely to happen. Thus, you can sometimes make aprogram use memory more efficiently by using blocks of the same size formany different purposes.When you ask for memory blocks of a page or larger, @code{malloc} uses adifferent strategy; it rounds the size up to a multiple of a page, andit can coalesce and split blocks as needed.The reason for the two strategies is that it is important to allocateand free small blocks as fast as possible, but speed is less importantfor a large block since the program normally spends a fair amount oftime using it. Also, large blocks are normally fewer in number.Therefore, for large blocks, it makes sense to use a method which takesmore time to minimize the wasted space.@node Aligned Memory Blocks@subsection Allocating Aligned Memory Blocks@cindex page boundary@cindex alignment (with @code{malloc})@pindex stdlib.hThe address of a block returned by @code{malloc} or @code{realloc} inthe GNU system is always a multiple of eight. If you need a block whoseaddress is a multiple of a higher power of two than that, use@code{memalign} or @code{valloc}. These functions are declared in@file{stdlib.h}.With the GNU library, you can use @code{free} to free the blocks that@code{memalign} and @code{valloc} return. That does not work in BSD,however---BSD does not provide any way to free such blocks.@comment malloc.h stdlib.h@comment BSD@deftypefun {void *} memalign (size_t @var{size}, size_t @var{boundary})The @code{memalign} function allocates a block of @var{size} bytes whoseaddress is a multiple of @var{boundary}. The @var{boundary} must be apower of two! The function @code{memalign} works by calling@code{malloc} to allocate a somewhat larger block, and then returning anaddress within the block that is on the specified boundary.@end deftypefun@comment malloc.h stdlib.h@comment BSD@deftypefun {void *} valloc (size_t @var{size})Using @code{valloc} is like using @code{memalign} and passing the page sizeas the value of the second argument. It is implemented like this:@smallexamplevoid *valloc (size_t size)@{ return memalign (size, getpagesize ());@}@end smallexample@c !!! xref getpagesize@end deftypefun@node Heap Consistency Checking@subsection Heap Consistency Checking@cindex heap consistency checking@cindex consistency checking, of heapYou can ask @code{malloc} to check the consistency of dynamic storage byusing the @code{mcheck} function. This function is a GNU extension,declared in @file{malloc.h}.@pindex malloc.h@comment malloc.h@comment GNU@deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))Calling @code{mcheck} tells @code{malloc} to perform occasionalconsistency checks. These will catch things such as writingpast the end of a block that was allocated with @code{malloc}.The @var{abortfn} argument is the function to call when an inconsistencyis found. If you supply a null pointer, then @code{mcheck} uses adefault function which prints a message and calls @code{abort}(@pxref{Aborting a Program}). The function you supply is called withone argument, which says what sort of inconsistency was detected; itstype is described below.It is too late to begin allocation checking once you have allocatedanything with @code{malloc}. So @code{mcheck} does nothing in thatcase. The function returns @code{-1} if you call it too late, and@code{0} otherwise (when it is successful).The easiest way to arrange to call @code{mcheck} early enough is to usethe option @samp{-lmcheck} when you link your program; then you don'tneed to modify your program source at all.@end deftypefun@deftypefun {enum mcheck_status} mprobe (void *@var{pointer})The @code{mprobe} function lets you explicitly check for inconsistenciesin a particular allocated block. You must have already called@code{mcheck} at the beginning of the program, to do its occasionalchecks; calling @code{mprobe} requests an additional consistency checkto be done at the time of the call.The argument @var{pointer} must be a pointer returned by @code{malloc}or @code{realloc}. @code{mprobe} returns a value that says whatinconsistency, if any, was found. The values are described below.@end deftypefun@deftp {Data Type} {enum mcheck_status}This enumerated type describes what kind of inconsistency was detectedin an allocated block, if any. Here are the possible values:@table @code@item MCHECK_DISABLED@code{mcheck} was not called before the first allocation.No consistency checking can be done.@item MCHECK_OKNo inconsistency detected.@item MCHECK_HEADThe data immediately before the block was modified.This commonly happens when an array index or pointeris decremented too far.@item MCHECK_TAILThe data immediately after the block was modified.This commonly happens when an array index or pointeris incremented too far.@item MCHECK_FREEThe block was already freed.@end table@end deftp@node Hooks for Malloc@subsection Storage Allocation Hooks@cindex allocation hooks, for @code{malloc}The GNU C library lets you modify the behavior of @code{malloc},@code{realloc}, and @code{free} by specifying appropriate hookfunctions. You can use these hooks to help you debug programs that usedynamic storage allocation, for example.The hook variables are declared in @file{malloc.h}.@pindex malloc.h@comment malloc.h@comment GNU@defvar __malloc_hookThe value of this variable is a pointer to function that @code{malloc}uses whenever it is called. You should define this function to looklike @code{malloc}; that is, like:@smallexamplevoid *@var{function} (size_t @var{size})@end smallexample@end defvar@comment malloc.h@comment GNU@defvar __realloc_hookThe value of this variable is a pointer to function that @code{realloc}uses whenever it is called. You should define this function to looklike @code{realloc}; that is, like:@smallexamplevoid *@var{function} (void *@var{ptr}, size_t @var{size})@end smallexample@end defvar@comment malloc.h@comment GNU@defvar __free_hookThe value of this variable is a pointer to function that @code{free}uses whenever it is called. You should define this function to looklike @code{free}; that is, like:@smallexamplevoid @var{function} (void *@var{ptr})@end smallexample@end defvarYou must make sure that the function you install as a hook for one ofthese functions does not call that function recursively without restoringthe old value of the hook first! Otherwise, your program will get stuckin an infinite recursion.Here is an example showing how to use @code{__malloc_hook} properly. Itinstalls a function that prints out information every time @code{malloc}is called.@smallexamplestatic void *(*old_malloc_hook) (size_t);static void *my_malloc_hook (size_t size)@{ void *result; __malloc_hook = old_malloc_hook; result = malloc (size); __malloc_hook = my_malloc_hook; printf ("malloc (%u) returns %p\n", (unsigned int) size, result); return result;@}main ()@{ ... old_malloc_hook = __malloc_hook; __malloc_hook = my_malloc_hook; ...@}@end smallexampleThe @code{mcheck} function (@pxref{Heap Consistency Checking}) works byinstalling such hooks.@c __morecore, __after_morecore_hook are undocumented@c It's not clear whether to document them.@node Statistics of Malloc@subsection Statistics for Storage Allocation with @code{malloc}@cindex allocation statisticsYou can get information about dynamic storage allocation by calling the@code{mstats} function. This function and its associated data type aredeclared in @file{malloc.h}; they are a GNU extension.@pindex malloc.h@comment malloc.h@comment GNU@deftp {Data Type} {struct mstats}This structure type is used to return information about the dynamicstorage allocator. It contains the following members:@table @code@item size_t bytes_totalThis is the total size of memory managed by @code{malloc}, in bytes.@item size_t chunks_usedThis is the number of chunks in use. (The storage allocator internallygets chunks of memory from the operating system, and then carves them upto satisfy individual @code{malloc} requests; see @ref{Efficiency andMalloc}.)@item size_t bytes_usedThis is the number of bytes in use.@item size_t chunks_freeThis is the number of chunks which are free -- that is, that have beenallocated by the operating system to your program, but which are notnow being used.@item size_t bytes_freeThis is the number of bytes which are free.@end table@end deftp@comment malloc.h@comment GNU@deftypefun {struct mstats} mstats (void)This function returns information about the current dynamic memory usagein a structure of type @code{struct mstats}.@end deftypefun@node Summary of Malloc@subsection Summary of @code{malloc}-Related FunctionsHere is a summary of the functions that work with @code{malloc}:@table @code@item void *malloc (size_t @var{size})Allocate a block of @var{size} bytes. @xref{Basic Allocation}.@item void free (void *@var{addr})Free a block previously allocated by @code{malloc}. @xref{Freeing afterMalloc}.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -