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

📄 faqcatbafd.html

📁 this is a mirrored site c-faq. thought might need offline
💻 HTML
📖 第 1 页 / 共 4 页
字号:
within the same program.</p><p>Additional links:<a href="../../malloc/sd4.html" rel=subdocument>further reading</a><hr><hr><hr><a name="freesize"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/freesize.html"><!-- qtag -->Question 7.26</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How does <TT>free</TT> know how many bytes to free?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>The malloc/free implementationremembers the sizeof each blockas it is allocated,so it is not necessary to remind it of the size when freeing.(Typically, the size is stored adjacent to the allocated block,which iswhy things usually break badlyif the bounds of the allocated block areeven slightlyoverstepped;see also question<a href="faqcatbafd.html?sec=malloc#crash">7.19</a>.)<hr><hr><hr><a name="querysize"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/querysize.html"><!-- qtag -->Question 7.27</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>So can I query the malloc package to find out how big anallocated block is?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Unfortunately,there is no standard or portable way.(Some compilers provide nonstandard extensions.)If you needto know,you'll have tokeep track ofit yourself.(See also question <a href="faqcatbafd.html?sec=malloc#sizeof">7.28</a>.)<hr><hr><hr><a name="sizeof"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/sizeof.html"><!-- qtag -->Question 7.28</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>Why doesn't <TT>sizeof</TT> tell me the size ofthe block of memory pointed to by a pointer?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font><TT>sizeof</TT> tells you the size of the pointer.There is noportableway to find out the size of a <TT>malloc</TT>'ed block.(Remember, too,that <TT>sizeof</TT> operates at compile time,and see also question <a href="faqcatbafd.html?sec=malloc#querysize">7.27</a>.)<hr><hr><hr><a name="realloc"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/realloc.html"><!-- qtag -->Question 7.29</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>Having dynamically allocated an array(as in question <a href="faqcatca65.html?sec=aryptr#dynarray">6.14</a>),can I change its size?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Yes.Thisis exactly what <TT>realloc</TT> is for.Given a region of <TT>malloc</TT>ed memory(such as <TT>dynarray</TT> from question <a href="faqcatca65.html?sec=aryptr#dynarray">6.14</a>),its size can be changed using code like:<pre>	dynarray = realloc(dynarray, 20 * sizeof(int));</pre>Note that <TT>realloc</TT> may not always be able to enlarge<a href="../../malloc/shrink.html" rel=subdocument>[footnote]</a>memory regionsin-place.Whenit is able to,it simply gives you back the same pointer you handed it,butif it must go to some other part of memoryto find enough contiguous space,it will return adifferent pointer(and the previous pointer value will become unusable).</p><p>If<TT>realloc</TT>cannot find enoughspace at all,it returns a null pointer,and leaves the previous region allocated.<a href="../../malloc/realloctrash.html" rel=subdocument>[footnote]</a>Therefore,you usually don't want to immediately assign the new pointerto the old variable.Instead,use a temporary pointer:<pre>	#include &lt;stdio.h&gt;	#include &lt;stdlib.h&gt;	int *newarray = (int *)realloc((void *)dynarray, 20 * sizeof(int));	if(newarray != NULL)		dynarray = newarray;	else {		fprintf(stderr, "Can't reallocate memory\n");		/* dynarray remains allocated */	}</pre></p><p>When reallocating memory,be careful ifthere are any other pointerslying aroundwhich point into(``alias'')that memory:if <TT>realloc</TT>must locate the new regionsomewhere else,those other pointers must also be adjusted.Here is a (contrived,and careless of <TT>malloc</TT>'s return values) example:<pre>#include &lt;stdio.h&gt;#include &lt;stdlib.h&gt;#include &lt;string.h&gt;char *p, *p2, *newp;int tmpoffset;p = malloc(10);strcpy(p, "Hello,");		/* p is a string */p2 = strchr(p, ',');		/* p2 points into that string */tmpoffset = p2 - p;newp = realloc(p, 20);if(newp != NULL) {	p = newp;		/* p may have moved */	p2 = p + tmpoffset;	/* relocate p2 as well */	strcpy(p2, ", world!");}printf("%s\n", p);</pre>(It is safest to recompute pointers based on offsets,as in the code fragment above.The alternative--relocating pointersbased on the difference,<TT>newp&nbsp;-&nbsp;p</TT>,between the base pointer's valuebefore and after the <TT>realloc</TT>--is not guaranteed to work,because pointer subtraction is only definedwhen performed on pointers into the same object.See also question <a href="faqcatbafd.html?sec=malloc#ptrafterfree">7.21</a>.)</p><p>See also questions<a href="faqcatbafd.html?sec=malloc#cast">7.7</a>and<a href="faqcatbafd.html?sec=malloc#reallocnull">7.30</a>.</p><p>References:K&amp;R2 Sec. B5 p. 252<br>ISO Sec. 7.10.3.4<br>H&amp;S Sec. 16.3 pp. 387-8<hr><hr><hr><a name="reallocnull"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/reallocnull.html"><!-- qtag -->Question 7.30</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>Is it legal to pass a null pointer as the first argument to <TT>realloc</TT>?Why would you want to?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>ANSI C sanctionsthis usage(and the related <TT>realloc(</TT>...<TT>,&nbsp;0)</TT>, which frees),although several earlier implementations do not support it,so itmay not befully portable.Passing an initially-null pointer to <TT>realloc</TT> can make iteasier to write a self-starting incremental allocation algorithm.</p><p>Here is an example--thisfunction readsan arbitrarily-long lineinto dynamically-allocated memory,reallocating the input buffer as necessary.(The caller must <TT>free</TT> the returned pointerwhen it is no longer needed.)<pre>#include &lt;stdio.h&gt;#include &lt;stdlib.h&gt;/* read a line from fp into malloc'ed memory *//* returns NULL on EOF or error *//* (use feof or ferror to distinguish) */char *agetline(FILE *fp){	char *retbuf = NULL;	size_t nchmax = 0;	register int c;	size_t nchread = 0;	char *newbuf;	while((c = getc(fp)) != EOF) {		if(nchread &gt;= nchmax) {			nchmax += 20;			if(nchread &gt;= nchmax) {	/* in case nchmax overflowed */				free(retbuf);				return NULL;			}#ifdef SAFEREALLOC			newbuf = realloc(retbuf, nchmax + 1);#else			if(retbuf == NULL)	/* in case pre-ANSI realloc */				newbuf = malloc(nchmax + 1);			else	newbuf = realloc(retbuf, nchmax + 1);#endif						/* +1 for \0 */			if(newbuf == NULL) {				free(retbuf);				return NULL;			}			retbuf = newbuf;		}		if(c == '\n')			break;		retbuf[nchread++] = c;	}	if(retbuf != NULL) {		retbuf[nchread] = '\0';		newbuf = realloc(retbuf, nchread + 1);		if(newbuf != NULL)			retbuf = newbuf;	}	return retbuf;}</pre>(In production code,a line like <TT>nchmax&nbsp;+=&nbsp;20</TT>can prove troublesome,as the function may do lots of reallocating.Many programmers favor multiplicative reallocation,e.g. <TT>nchmax&nbsp;*=&nbsp;2</TT>,although it obviously isn'tquite asself-starting,and can run into problems if ithas to allocate a huge arraybut memory is limited.)</p><p>References:ISO Sec. 7.10.3.4<br>H&amp;S Sec. 16.3 p. 388<hr><hr><hr><a name="calloc"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/calloc.html"><!-- qtag -->Question 7.31</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What's the difference between <TT>calloc</TT> and <TT>malloc</TT>?Which should Iuse?Is it safe to take advantage of <TT>calloc</TT>'szero-filling?Does <TT>free</TT> workon memory allocated with <TT>calloc</TT>,or do youneed a <TT>cfree</TT>?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font><TT>calloc(m, n)</TT> is essentially equivalent to<pre>p&nbsp;=&nbsp;malloc(m&nbsp;*&nbsp;n);memset(p,&nbsp;0,&nbsp;m&nbsp;*&nbsp;n);</pre></p><p>There is no important difference betweenthe twoother than the number of argumentsand the zero fill.<a href="../../malloc/callocvslazy.html" rel=subdocument>[footnote]</a></p><p>Use whichever function is convenient.Don't rely on <TT>calloc</TT>'s zero fill too much(see below);usually,it's best to initialize data structures yourself,on a field-by-field basis,especially if there are pointer fields.</p><p><TT>calloc</TT>'szero fill is all-bits-zero,andis therefore guaranteed to yield the value 0for all integral types(including<TT>'\0'</TT>forcharacter types).Butitdoes <em>not</em>guarantee useful null pointer values(seesection<a href="faqcat1f1a.html?sec=null#index">5</a> of this list)or floating-point zero values.</p><p><TT>free</TT>isproperlyused to free the memory allocatedby <TT>calloc</TT>;there is no Standard <TT>cfree</TT> function.</p><p>One imagined distinction that is <em>not</em> significantbetween <TT>malloc</TT> and <TT>calloc</TT>is whethera single elementor an array of elementsis being allocated.Though <TT>calloc</TT>'s two-argument calling convention suggests that itis supposed tobe used to allocate an array of <TT>m</TT> items of size <TT>n</TT>,there is no suchrequirement;it is perfectlypermissibleto allocate one item with <TT>calloc</TT>(by passing one argument as 1)or to allocate an array with <TT>malloc</TT>(by doing the multiplication yourself;see for examplethe code fragment inquestion <a href="faqcatca65.html?sec=aryptr#dynarray">6.14</a>).(Nor does structure padding enter into the question;any padding necessaryto make arrays of structures work correctlyis always handled by the compiler,and reflected by <TT>sizeof</TT>.See question <a href="faqcat6b6b.html?sec=struct#endpad">2.13</a>.)</p><p>References:ISO Sec. 7.10.3 to 7.10.3.2<br>H&amp;S Sec. 16.1 p. 386, Sec. 16.2 p. 386<br>PCS Sec. 11 pp. 141,142<hr><hr><hr><a name="alloca"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/alloca.html"><!-- qtag -->Question 7.32</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What is <TT>alloca</TT> and why is its use discouraged?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font><TT>alloca</TT>allocates memory which is automatically freed when thefunction which called <TT>alloca</TT> returns.That is, memory allocated with <TT>alloca</TT> is local to a particularfunction's ``stack frame'' or context.</p><p><TT>alloca</TT> cannot be writtenportably,<a href="../../malloc/allocaport.html" rel=subdocument>[footnote]</a>andis difficult to implement on machines without aconventionalstack.Its use is problematical(and theobviousimplementation on a stack-based machine fails) when itsreturn value is passed directly to another function, as in<TT>fgets(alloca(100),&nbsp;100,&nbsp;stdin)</TT>.<a href="../../malloc/allocastack.html" rel=subdocument>[footnote]</a></p><p>For these reasons, <TT>alloca</TT>is not Standard andcannot be used in programs which must be widelyportable,no matter how useful it might be.Now that C99 supports variable-length arrays (VLA's),they can be used to more cleanly accomplishmost of the tasks which <TT>alloca</TT> used to be put to.</p><p>See also question <a href="faqcatbafd.html?sec=malloc#local">7.22</a>.</p><p>Additional links:an<a href="../../malloc/alloca.glb.html">article by Gordon L. Burditt</a>describing difficulties in implementing and using <TT>alloca</TT></p><p>References:Rationale Sec. 4.10.3<hr><hr><hr><hr><p>Read sequentially:<a href="faqcatca65.html?sec=aryptr" rev=precedes>prev</a><a href="faqcate107.html?sec=charstring" rel=precedes>next</a><a href="faqcat.html" rev=subdocument>up</a></p><hr><p><br><!-- lastfooter --><a href="../../about.html">about this FAQ list</a>&nbsp;<a href="../../eskimo.html">about eskimo</a>&nbsp;<a href="../../search.html">search</a>&nbsp;<a href="../../feedback.html">feedback</a>&nbsp;<a href="../../malloc/copyright.html">copyright</a><p>Hosted by<a href="http://www.eskimo.com/"><img src="../../../www.eskimo.com/img/link/eskitiny.gif" alt="Eskimo North"></a></body><!-- Mirrored from c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=malloc by HTTrack Website Copier/3.x [XR&CO'2008], Sat, 14 Mar 2009 07:57:56 GMT --></html>

⌨️ 快捷键说明

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