?? library_3.html
字號(hào):
<!-- 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 space
under explicit program control. They vary in generality and in
efficiency.
<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 more
efficient 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 that
will 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 programs
determine as they are running where to store some information. You need
dynamic allocation when the number of memory blocks you need, or how
long 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 the
storage dynamically and make it dynamically larger as you read more of the
line.
<P>
Or, you may need a block for each record or each definition in the input
data; since you can't know in advance how many there will be, you must
allocate 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 an
action that the program requests explicitly. You call a function or macro
when you want to allocate space, and specify the size with an argument. If
you 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 variables
in C programs:
<P>
<UL>
<LI>
<DFN>Static allocation</DFN> is what happens when you declare a static
variable. Each static variable defines one block of space, of a fixed
size. The space is allocated once, when your program is started, and
is never freed.
<P>
<LI>
<DFN>Automatic allocation</DFN> happens when you declare an automatic
variable, such as a function argument or a local variable. The space
for an automatic variable is allocated when the compound statement
containing the declaration is entered, and is freed when that
compound statement is exited.
<P>
In GNU C, the length of the automatic storage can be an expression
that varies. In other C implementations, it must be a constant.
</UL>
<P>
Dynamic allocation is not supported by C variables; there is no storage
class "dynamic", and there can never be a C variable whose value is
stored in dynamically allocated space. The only way to refer to
dynamically allocated space is through a pointer. Because it is less
convenient, and because the actual process of dynamic allocation
requires more computation time, programmers use dynamic allocation only
when 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>struct
foobar</CODE> whose contents are the dynamically allocated space. But you can
declare a variable of pointer type <CODE>struct foobar *</CODE> and assign it the
address 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>. It
allows you to allocate blocks of memory of any size at any time, make
them bigger or smaller at any time, and free the blocks individually at
any 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 for
this 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 object
that you want to store in the block. Here we show an example of doing
so, 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 variable
without a cast, because ANSI C automatically converts the type
<CODE>void *</CODE> to another type of pointer when necessary. But the cast
is necessary in contexts other than assignment operators or if you might
want 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 is
because a string is terminated with a null character that doesn't count
in 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 is
useful to write a subroutine that calls <CODE>malloc</CODE> and reports an
error if the value is a null pointer, returning only if the value is
nonzero. This function is conventionally called <CODE>xmalloc</CODE>. Here
it 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 into
a 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 so
that it can hold any type of data. In the GNU system, the address is
always a multiple of eight; if the size of block is 16 or more, then the
address 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 be
in use for something else; perhaps a block already allocated by another
call to <CODE>malloc</CODE>. If you attempt to treat the block as longer than
you 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 the
contents of another block. If you have already allocated a block and
discover 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 the
function <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 at
by <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 for
backward compatibility with SunOS; you should use <CODE>free</CODE> instead.
<P>
Freeing a block alters the contents of the block. <STRONG>Do not expect to
find any data (such as a pointer to the next block in a chain of blocks) in
the block after freeing it.</STRONG> Copy whatever you need out of the block before
freeing it! Here is an example of the proper way to free all the blocks in
a chain, and the strings that they point to:
<P>
<PRE>
struct chain
{
struct chain *next;
char *name;
}
void
free_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 operating
system and make the process smaller. Usually, all it can do is allow a
later 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 internally
by <CODE>malloc</CODE>.
<P>
There is no point in freeing blocks at the end of a program, because all
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -