⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 memory.texi

📁 一个C源代码分析器
💻 TEXI
📖 第 1 页 / 共 5 页
字号:
@comment !!! describe mmap et al (here?)@c !!! doc brk/sbrk@node Memory Allocation, Character Handling, Error Reporting, Top@chapter Memory Allocation@cindex memory allocation@cindex storage allocationThe GNU system provides several methods for allocating memory spaceunder explicit program control.  They vary in generality and inefficiency.@iftex@itemize @bullet@itemThe @code{malloc} facility allows fully general dynamic allocation.@xref{Unconstrained Allocation}.@itemObstacks are another facility, less general than @code{malloc} but moreefficient and convenient for stacklike allocation.  @xref{Obstacks}.@itemThe function @code{alloca} lets you allocate storage dynamically thatwill be freed automatically.  @xref{Variable Size Automatic}.@end itemize@end iftex@menu* Memory Concepts::             An introduction to concepts and terminology.* Dynamic Allocation and C::    How to get different kinds of allocation in C.* Unconstrained Allocation::    The @code{malloc} facility allows fully general		 		 dynamic allocation.* Obstacks::                    Obstacks are less general than malloc				 but more efficient and convenient.* Variable Size Automatic::     Allocation of variable-sized blocks				 of automatic storage that are freed when the				 calling function returns.* Relocating Allocator::        Waste less memory, if you can tolerate				 automatic relocation of the blocks you get.* Memory Warnings::		Getting warnings when memory is nearly full.@end menu@node Memory Concepts@section Dynamic Memory Allocation Concepts@cindex dynamic allocation@cindex static allocation@cindex automatic allocation@dfn{Dynamic memory allocation} is a technique in which programsdetermine as they are running where to store some information.  You needdynamic allocation when the number of memory blocks you need, or howlong you continue to need them, depends on the data you are working on.For example, you may need a block to store a line read from an input file;since there is no limit to how long a line can be, you must allocate thestorage dynamically and make it dynamically larger as you read more of theline.Or, you may need a block for each record or each definition in the inputdata; since you can't know in advance how many there will be, you mustallocate a new block for each record or definition as you read it.When you use dynamic allocation, the allocation of a block of memory is anaction that the program requests explicitly.  You call a function or macrowhen you want to allocate space, and specify the size with an argument.  Ifyou want to free the space, you do so by calling another function or macro.You can do these things whenever you want, as often as you want.@node Dynamic Allocation and C@section Dynamic Allocation and CThe C language supports two kinds of memory allocation through the variablesin C programs:@itemize @bullet@item@dfn{Static allocation} is what happens when you declare a static orglobal variable.  Each static or global variable defines one block ofspace, of a fixed size.  The space is allocated once, when your programis started, and is never freed.@item@dfn{Automatic allocation} happens when you declare an automaticvariable, such as a function argument or a local variable.  The spacefor an automatic variable is allocated when the compound statementcontaining the declaration is entered, and is freed when thatcompound statement is exited.In GNU C, the length of the automatic storage can be an expressionthat varies.  In other C implementations, it must be a constant.@end itemizeDynamic allocation is not supported by C variables; there is no storageclass ``dynamic'', and there can never be a C variable whose value isstored in dynamically allocated space.  The only way to refer todynamically allocated space is through a pointer.  Because it is lessconvenient, and because the actual process of dynamic allocationrequires more computation time, programmers use dynamic allocation onlywhen neither static nor automatic allocation will serve.For example, if you want to allocate dynamically some space to hold a@code{struct foobar}, you cannot declare a variable of type @code{structfoobar} whose contents are the dynamically allocated space.  But you candeclare a variable of pointer type @code{struct foobar *} and assign it theaddress of the space.  Then you can use the operators @samp{*} and@samp{->} on this pointer variable to refer to the contents of the space:@smallexample@{  struct foobar *ptr     = (struct foobar *) malloc (sizeof (struct foobar));  ptr->name = x;  ptr->next = current_foobar;  current_foobar = ptr;@}@end smallexample@node Unconstrained Allocation@section Unconstrained Allocation@cindex unconstrained storage allocation@cindex @code{malloc} function@cindex heap, dynamic allocation fromThe most general dynamic allocation facility is @code{malloc}.  Itallows you to allocate blocks of memory of any size at any time, makethem bigger or smaller at any time, and free the blocks individually atany time (or never).@menu* Basic Allocation::            Simple use of @code{malloc}.* Malloc Examples::             Examples of @code{malloc}.  @code{xmalloc}.* Freeing after Malloc::        Use @code{free} to free a block you				 got with @code{malloc}.* Changing Block Size::         Use @code{realloc} to make a block				 bigger or smaller.* Allocating Cleared Space::    Use @code{calloc} to allocate a				 block and clear it.* Efficiency and Malloc::       Efficiency considerations in use of				 these functions.* Aligned Memory Blocks::       Allocating specially aligned memory:				 @code{memalign} and @code{valloc}.* Heap Consistency Checking::   Automatic checking for errors.* Hooks for Malloc::            You can use these hooks for debugging				 programs that use @code{malloc}.* Statistics of Malloc::        Getting information about how much				 memory your program is using.* Summary of Malloc::           Summary of @code{malloc} and related functions.@end menu@node Basic Allocation@subsection Basic Storage Allocation@cindex allocation of memory with @code{malloc}To allocate a block of memory, call @code{malloc}.  The prototype forthis function is in @file{stdlib.h}.@pindex stdlib.h@comment malloc.h stdlib.h@comment ANSI@deftypefun {void *} malloc (size_t @var{size})This function returns a pointer to a newly allocated block @var{size}bytes long, or a null pointer if the block could not be allocated.@end deftypefunThe contents of the block are undefined; you must initialize it yourself(or use @code{calloc} instead; @pxref{Allocating Cleared Space}).Normally you would cast the value as a pointer to the kind of objectthat you want to store in the block.  Here we show an example of doingso, and of initializing the space with zeros using the library function@code{memset} (@pxref{Copying and Concatenation}):@smallexamplestruct foo *ptr;@dots{}ptr = (struct foo *) malloc (sizeof (struct foo));if (ptr == 0) abort ();memset (ptr, 0, sizeof (struct foo));@end smallexampleYou can store the result of @code{malloc} into any pointer variablewithout a cast, because ANSI C automatically converts the type@code{void *} to another type of pointer when necessary.  But the castis necessary in contexts other than assignment operators or if you mightwant your code to run in traditional C.Remember that when allocating space for a string, the argument to@code{malloc} must be one plus the length of the string.  This isbecause a string is terminated with a null character that doesn't countin the ``length'' of the string but does need space.  For example:@smallexamplechar *ptr;@dots{}ptr = (char *) malloc (length + 1);@end smallexample@noindent@xref{Representation of Strings}, for more information about this.@node Malloc Examples@subsection Examples of @code{malloc}If no more space is available, @code{malloc} returns a null pointer.You should check the value of @emph{every} call to @code{malloc}.  It isuseful to write a subroutine that calls @code{malloc} and reports anerror if the value is a null pointer, returning only if the value isnonzero.  This function is conventionally called @code{xmalloc}.  Hereit is:@smallexamplevoid *xmalloc (size_t size)@{  register void *value = malloc (size);  if (value == 0)    fatal ("virtual memory exhausted");  return value;@}@end smallexampleHere is a real example of using @code{malloc} (by way of @code{xmalloc}).The function @code{savestring} will copy a sequence of characters intoa newly allocated null-terminated string:@smallexamplechar *savestring (const char *ptr, size_t len)@{  register char *value = (char *) xmalloc (len + 1);  memcpy (value, ptr, len);  value[len] = '\0';  return value;@}@end smallexampleThe block that @code{malloc} gives you is guaranteed to be aligned sothat it can hold any type of data.  In the GNU system, the address isalways a multiple of eight; if the size of block is 16 or more, then theaddress is always a multiple of 16.  Only rarely is any higher boundary(such as a page boundary) necessary; for those cases, use@code{memalign} or @code{valloc} (@pxref{Aligned Memory Blocks}).Note that the memory located after the end of the block is likely to bein use for something else; perhaps a block already allocated by anothercall to @code{malloc}.  If you attempt to treat the block as longer thanyou asked for it to be, you are liable to destroy the data that@code{malloc} uses to keep track of its blocks, or you may destroy thecontents of another block.  If you have already allocated a block anddiscover you want it to be bigger, use @code{realloc} (@pxref{ChangingBlock Size}).@node Freeing after Malloc@subsection Freeing Memory Allocated with @code{malloc}@cindex freeing memory allocated with @code{malloc}@cindex heap, freeing memory fromWhen you no longer need a block that you got with @code{malloc}, use thefunction @code{free} to make the block available to be allocated again.The prototype for this function is in @file{stdlib.h}.@pindex stdlib.h@comment malloc.h stdlib.h@comment ANSI@deftypefun void free (void *@var{ptr})The @code{free} function deallocates the block of storage pointed atby @var{ptr}.@end deftypefun@comment stdlib.h@comment Sun@deftypefun void cfree (void *@var{ptr})This function does the same thing as @code{free}.  It's provided forbackward compatibility with SunOS; you should use @code{free} instead.@end deftypefunFreeing a block alters the contents of the block.  @strong{Do not expect tofind any data (such as a pointer to the next block in a chain of blocks) inthe block after freeing it.}  Copy whatever you need out of the block beforefreeing it!  Here is an example of the proper way to free all the blocks ina chain, and the strings that they point to:@smallexamplestruct chain  @{    struct chain *next;    char *name;  @}voidfree_chain (struct chain *chain)@{  while (chain != 0)    @{      struct chain *next = chain->next;      free (chain->name);      free (chain);      chain = next;    @}@}@end smallexampleOccasionally, @code{free} can actually return memory to the operatingsystem and make the process smaller.  Usually, all it can do is allow alater call to @code{malloc} to reuse the space.  In the meantime, thespace remains in your program as part of a free-list used internally by@code{malloc}.There is no point in freeing blocks at the end of a program, because allof the program's space is given back to the system when the processterminates.@node Changing Block Size@subsection Changing the Size of a Block@cindex changing the size of a block (@code{malloc})Often you do not know for certain how big a block you will ultimately needat the time you must begin to use the block.  For example, the block mightbe a buffer that you use to hold a line being read from a file; no matterhow long you make the buffer initially, you may encounter a line that islonger.You can make the block longer by calling @code{realloc}.  This functionis declared in @file{stdlib.h}.@pindex stdlib.h@comment malloc.h stdlib.h@comment ANSI@deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})The @code{realloc} function changes the size of the block whose address is@var{ptr} to be @var{newsize}.Since the space after the end of the block may be in use, @code{realloc}may find it necessary to copy the block to a new address where more freespace is available.  The value of @code{realloc} is the new address of theblock.  If the block needs to be moved, @code{realloc} copies the oldcontents.If you pass a null pointer for @var{ptr}, @code{realloc} behaves justlike @samp{malloc (@var{newsize})}.  This can be convenient, but bewarethat older implementations (before ANSI C) may not support thisbehavior, and will probably crash when @code{realloc} is passed a nullpointer.@end deftypefunLike @code{malloc}, @code{realloc} may return a null pointer if no

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -