📄 library_3.html
字号:
<!-- This HTML file has been created by texi2html 1.27 from library.texinfo on 3 March 1994 --><TITLE>The GNU C Library - Memory Allocation</TITLE><P>Go to the <A HREF="library_2.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_2.html">previous</A>, <A HREF="library_4.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_4.html">next</A> section.<P><A NAME="IDX130"></A><A NAME="IDX131"></A><H1><A NAME="SEC18" HREF="library_toc.html#SEC18" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC18">Memory Allocation</A></H1><P>The GNU system provides several methods for allocating memory spaceunder explicit program control. They vary in generality and inefficiency.<P><UL><LI>The <CODE>malloc</CODE> facility allows fully general dynamic allocation.See section <A HREF="library_3.html#SEC21" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_3.html#SEC21">Unconstrained Allocation</A>.<P><LI>Obstacks are another facility, less general than <CODE>malloc</CODE> but moreefficient and convenient for stacklike allocation. See section <A HREF="library_3.html#SEC33" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_3.html#SEC33">Obstacks</A>.<P><LI>The function <CODE>alloca</CODE> lets you allocate storage dynamically thatwill be freed automatically. See section <A HREF="library_3.html#SEC45" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_3.html#SEC45">Automatic Storage with Variable Size</A>.</UL><P><A NAME="IDX132"></A><A NAME="IDX133"></A><A NAME="IDX134"></A><H2><A NAME="SEC19" HREF="library_toc.html#SEC19" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC19">Dynamic Memory Allocation Concepts</A></H2><P><DFN>Dynamic memory allocation</DFN> 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.<P>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.<P>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.<P>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.<P><H2><A NAME="SEC20" HREF="library_toc.html#SEC20" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC20">Dynamic Allocation and C</A></H2><P>The C language supports two kinds of memory allocation through the variablesin C programs:<P><UL><LI><DFN>Static allocation</DFN> is what happens when you declare a staticvariable. Each static variable defines one block of space, of a fixedsize. The space is allocated once, when your program is started, andis never freed.<P><LI><DFN>Automatic allocation</DFN> 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.<P>In GNU C, the length of the automatic storage can be an expressionthat varies. In other C implementations, it must be a constant.</UL><P>Dynamic 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.<P>For example, if you want to allocate dynamically some space to hold a<CODE>struct foobar</CODE>, you cannot declare a variable of type <CODE>structfoobar</CODE> whose contents are the dynamically allocated space. But you candeclare a variable of pointer type <CODE>struct foobar *</CODE> and assign it theaddress of the space. Then you can use the operators <SAMP>`*'</SAMP> and<SAMP>`->'</SAMP> on this pointer variable to refer to the contents of the space:<P><PRE>{ struct foobar *ptr = (struct foobar *) malloc (sizeof (struct foobar)); ptr->name = x; ptr->next = current_foobar; current_foobar = ptr;}</PRE><P><A NAME="IDX135"></A><A NAME="IDX136"></A><A NAME="IDX137"></A><H2><A NAME="SEC21" HREF="library_toc.html#SEC21" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC21">Unconstrained Allocation</A></H2><P>The most general dynamic allocation facility is <CODE>malloc</CODE>. 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).<P><A NAME="IDX138"></A><H3><A NAME="SEC22" HREF="library_toc.html#SEC22" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC22">Basic Storage Allocation</A></H3><P>To allocate a block of memory, call <CODE>malloc</CODE>. The prototype forthis function is in <TT>`stdlib.h'</TT>.<A NAME="IDX139"></A><P><A NAME="IDX140"></A><U>Function:</U> void * <B>malloc</B> <I>(size_t <VAR>size</VAR>)</I><P>This function returns a pointer to a newly allocated block <VAR>size</VAR>bytes long, or a null pointer if the block could not be allocated.<P>The contents of the block are undefined; you must initialize it yourself(or use <CODE>calloc</CODE> instead; see section <A HREF="library_3.html#SEC26" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_3.html#SEC26">Allocating Cleared Space</A>).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</CODE> (see section <A HREF="library_5.html#SEC61" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_5.html#SEC61">Copying and Concatenation</A>):<P><PRE>struct foo *ptr;...ptr = (struct foo *) malloc (sizeof (struct foo));if (ptr == 0) abort ();memset (ptr, 0, sizeof (struct foo));</PRE><P>You can store the result of <CODE>malloc</CODE> into any pointer variablewithout a cast, because ANSI C automatically converts the type<CODE>void *</CODE> 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.<P>Remember that when allocating space for a string, the argument to<CODE>malloc</CODE> 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:<P><PRE>char *ptr;...ptr = (char *) malloc (length + 1);</PRE><P>See section <A HREF="library_5.html#SEC58" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_5.html#SEC58">Representation of Strings</A>, for more information about this.<P><H3><A NAME="SEC23" HREF="library_toc.html#SEC23" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC23">Examples of <CODE>malloc</CODE></A></H3><P>If no more space is available, <CODE>malloc</CODE> returns a null pointer.You should check the value of <EM>every</EM> call to <CODE>malloc</CODE>. It isuseful to write a subroutine that calls <CODE>malloc</CODE> and reports anerror if the value is a null pointer, returning only if the value isnonzero. This function is conventionally called <CODE>xmalloc</CODE>. Hereit is:<P><PRE>void *xmalloc (size_t size){ register void *value = malloc (size); if (value == 0) fatal ("virtual memory exhausted"); return value;}</PRE><P>Here is a real example of using <CODE>malloc</CODE> (by way of <CODE>xmalloc</CODE>).The function <CODE>savestring</CODE> will copy a sequence of characters intoa newly allocated null-terminated string:<P><PRE>char *savestring (const char *ptr, size_t len){ register char *value = (char *) xmalloc (len + 1); memcpy (value, ptr, len); value[len] = 0; return value;}</PRE><P>The block that <CODE>malloc</CODE> 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</CODE> or <CODE>valloc</CODE> (see section <A HREF="library_3.html#SEC28" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_3.html#SEC28">Allocating Aligned Memory Blocks</A>).<P>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</CODE>. 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</CODE> 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</CODE> (see section <A HREF="library_3.html#SEC25" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_3.html#SEC25">Changing the Size of a Block</A>).<P><A NAME="IDX141"></A><A NAME="IDX142"></A><H3><A NAME="SEC24" HREF="library_toc.html#SEC24" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC24">Freeing Memory Allocated with <CODE>malloc</CODE></A></H3><P>When you no longer need a block that you got with <CODE>malloc</CODE>, use thefunction <CODE>free</CODE> to make the block available to be allocated again.The prototype for this function is in <TT>`stdlib.h'</TT>.<A NAME="IDX143"></A><P><A NAME="IDX144"></A><U>Function:</U> void <B>free</B> <I>(void *<VAR>ptr</VAR>)</I><P>The <CODE>free</CODE> function deallocates the block of storage pointed atby <VAR>ptr</VAR>.<P><A NAME="IDX145"></A><U>Function:</U> void <B>cfree</B> <I>(void *<VAR>ptr</VAR>)</I><P>This function does the same thing as <CODE>free</CODE>. It's provided forbackward compatibility with SunOS; you should use <CODE>free</CODE> instead.<P>Freeing 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.</STRONG> 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:<P><PRE>struct 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; }}</PRE><P>Occasionally, <CODE>free</CODE> can actually return memory to the operatingsystem and make the process smaller. Usually, all it can do is allow alater later call to <CODE>malloc</CODE> to reuse the space. In the mean time,the space remains in your program as part of a free-list used internallyby <CODE>malloc</CODE>.<P>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.<P><A NAME="IDX146"></A><H3><A NAME="SEC25" HREF="library_toc.html#SEC25" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC25">Changing the Size of a Block</A></H3><P>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -