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

📄 faqcatbafd.html

📁 this is a mirrored site c-faq. thought might need offline
💻 HTML
📖 第 1 页 / 共 4 页
字号:
even before you multiply it by <TT>sizeof(double)</TT>.If youneed to allocatethis muchmemory,you'll have to be careful.If <TT>size_t</TT>(the type accepted by <TT>malloc</TT>)is a 32-bit type on your machine,but <TT>int</TT> is 16 bits,you might be able to get away with writing<TT>300 * (300 * sizeof(double))</TT>(see question <a href="faqcatee08.html?sec=expr#intoverflow1">3.14</a>).Otherwise,you'll have to breakyour data structureup into smaller chunks,or use a 32-bit machineor compiler,or usesome nonstandard memory allocation functions.See alsoquestions <a href="faqcatbafd.html?sec=malloc#sizetlong">7.15</a> and <a href="faqcatea63.html?sec=osdep#bigdatastr">19.23</a>.<hr><hr><hr><a name="segment"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/segment.html"><!-- qtag -->Question 7.17</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I've got 8 meg of memory in my PC.Why can I only seem to <TT>malloc</TT> 640K or so?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Under the segmented architecture of PC compatibles,it can bedifficult to use more than 640Kwith any degree of transparency,especially under MS-DOS.Seealsoquestion <a href="faqcatea63.html?sec=osdep#bigdatastr">19.23</a>.<hr><hr><hr><a name="efficiency"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/efficiency.html"><!-- qtag -->Question 7.18</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>My application depends heavily ondynamic allocation of nodes for data structures,and <TT>malloc</TT>/<TT>free</TT> overheadisbecominga bottleneck.What canI do?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>One improvement,which is particularly attractive if all nodes are the same size,is to place unused nodes on your own free list,rather than actually <TT>free</TT>ing them.(This approach works wellwhen one kind of data structure dominates a program's memory use,but it can cause as many problems as it solvesif so much memory is tied up in thelist of unused nodesthat it isn't available for other purposes.)<hr><hr><hr><a name="crash"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/crash.html"><!-- qtag -->Question 7.19</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>My program is crashing, apparently somewhere down inside<TT>malloc</TT>,but I can't see anything wrong with it.Is there a bug in <TT>malloc</TT>?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>It is unfortunately very easy to corrupt<TT>malloc</TT>'s internal data structures,and the resulting problems can bestubborn.The most common source of problems is writing more to a<TT>malloc</TT>'ed region than it was allocated to hold;a particularly common bug is to <TT>malloc(strlen(s))</TT>instead of <TT>strlen(s)&nbsp;+&nbsp;1</TT>.<a href="../../malloc/morebugs.html" rel=subdocument>[footnote]</a>Other problems may involveusing pointers tomemory that has been freed,freeing pointers twice,freeing pointers notobtained from <TT>malloc</TT>,<TT>free</TT>ing null pointers,allocating 0-sized objects(see question <a href="faqcat7d4b.html?sec=ansi#malloc0">11.26</a>),or trying to <TT>realloc</TT> a null pointer(see question<a href="faqcatbafd.html?sec=malloc#reallocnull">7.30</a>).(The last three--<TT>free</TT>ing null pointers,allocating 0-sized objects,and<TT>realloc</TT>ing a null pointer--are sanctioned by the Standard,thougholder implementations often have problems.)Consequences ofany of these errorscan show uplong after the actual mistakeandin unrelated sections of code,making diagnosis of the problem quite difficult.</p><p>Most implementations of <TT>malloc</TT> are particularly vulnerableto these problems because they store crucialpieces ofinternalinformation directly adjacent to the blocks of memorythey return,making themeasy prey for stray user pointers.</p><p>See also questions<a href="faqcatbafd.html?sec=malloc#sizetlong">7.15</a>,<a href="faqcatbafd.html?sec=malloc#freesize">7.26</a>,<a href="faqcat5e04.html?sec=strangeprob#segv">16.8</a>,and<a href="faqcatccbd.html?sec=resources#mallocdbg">18.2</a>.<hr><hr><hr><a name="noscale"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/noscale.html"><!-- qtag -->Question 7.19b</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I'm dynamically allocating an array, like this:<pre>	int *iarray = (int *)malloc(nints);</pre><TT>malloc</TT> isn't returning NULL,but the code isn't working.</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font><TT>malloc</TT>is a low-level, typeless allocator.It doesn't knowhow you're going to use the memory;all it does is to allocateas many <em>bytes</em> of memory as you ask it.Therefore(except when you're allocating arrays of <TT>char</TT>)you mustmultiply by the size of the elements in the array you're allocating:<pre>	int *iarray = malloc(nints * sizeof(int));</pre>or<pre>	int *iarray = malloc(nints * sizeof(*iarray));</pre>(The latter fragment can be more reliableif the type of <TT>iarray</TT> might change,since there's only one place to change it.Also, the casts have been removed;see question <a href="faqcatbafd.html?sec=malloc#cast">7.7</a>.)Compare question <a href="faqcatabdc.html?sec=ptrs#explscale">4.4</a>,and see also question <a href="faqcatbafd.html?sec=malloc#sizeofchar">7.8</a>.<hr><hr><hr><a name="useafterfree"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/useafterfree.html"><!-- qtag -->Question 7.20</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>You can't use dynamically-allocated memory after you free it, can you?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>No.Some earlydocumentationfor <TT>malloc</TT> stated that the contents of freedmemorywere``left undisturbed,''butthis ill-advised guaranteewas neveruniversal and is not requiredby the C Standard.</p><p>Few programmers would use the contents of freed memorydeliberately, but it is easy to do so accidentally.Consider the following (correct) code for freeing a singly-linkedlist:<pre>	struct list *listp, *nextp;	for(listp = base; listp != NULL; listp = nextp) {		nextp = listp-&gt;next;		free(listp);	}</pre>and notice what would happenif the more-obvious loop iterationexpression <TT>listp&nbsp;=&nbsp;listp-&gt;next</TT>were used,without the temporary <TT>nextp</TT> pointer.</p><p>References:K&amp;R2 Sec. 7.8.5 p. 167<br>ISO Sec. 7.10.3<br>Rationale Sec. 4.10.3.2<br>H&amp;S Sec. 16.2 p. 387<br>CT&amp;P Sec. 7.10 p. 95<hr><hr><hr><a name="ptrafterfree"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/ptrafterfree.html"><!-- qtag -->Question 7.21</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>Why isn't a pointernullafter calling<TT>free</TT>?<br>How unsafe is it to use(assign, compare)a pointer value after it's been freed?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>When you call <TT>free</TT>,the memory pointed to by the passed pointer is freed,but the value of the pointer in the callerprobablyremains unchanged,becauseC's pass-by-valuesemanticsmean that called functionsnever permanentlychange the values of their arguments.(See also question <a href="faqcatabdc.html?sec=ptrs#passptrinit">4.8</a>.)</p><p>A pointervaluewhich has been freed is, strictly speaking, invalid,and <em>any</em> use of it,even if it is not dereferenced(i.e. even ifthe use of it is aseemingly innocuousassignment or comparison),can theoretically lead to trouble.(Wecan probably assume thatas a quality of implementation issue,most implementations willnot go out of their wayto generate exceptionsfor innocuous uses of invalidpointers,but the Standard is clearin saying thatnothing is guaranteed,andthere are system architecturesfor whichsuchexceptionswould be quite natural.)</p><p>When pointer variables(or fields within structures)are repeatedly allocated and freed within a program,it is often useful to set them to NULLimmediately after freeingthem,to explicitly record their state.</p><p>References:ISO Sec. 7.10.3<br>Rationale Sec. 3.2.2.3<br></p><hr><hr><hr><a name="local"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/local.html"><!-- qtag -->Question 7.22</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>When I call <TT>malloc</TT> to allocate memory for apointer which is local to a function,do I have to explicitly <TT>free</TT> it?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Yes.Remember that a pointer is different from what it points to.Localvariables<a href="../../malloc/auto.html" rel=subdocument>[footnote]</a>are deallocated when the function returns,but in the case of a pointer variable,this means that the pointer is deallocated,<em>not</em> what it points to.Memory allocated with <TT>malloc</TT> always persistsuntil you explicitly free it.(If the only pointer to a block of <TT>malloc</TT>'ed memory is a local pointer,and if that pointer disappears,there will be no way to freethat block.)In general,for every call to <TT>malloc</TT>,there should be a corresponding call to <TT>free</TT>.<hr><hr><hr><a name="freeforall"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/freeforall.html"><!-- qtag -->Question 7.23</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I'm allocating structures which contain pointers to otherdynamically-allocated objects.When I freea structure,do Ialsohave to free each subsidiary pointer?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Yes.<TT>malloc</TT> knows nothing about structure declarationsor about the contents of allocated memory;it especially does not knowwhether allocated memorycontains pointers to other allocated memory.In general,you must arrange that each pointer returned from <TT>malloc</TT>be individually passed to <TT>free</TT>,exactly once(if it is freed at all).</p><p>A good rule of thumbis that for each call to <TT>malloc</TT> in a program,you should be able topoint atthe call to <TT>free</TT>which frees the memory allocated by that <TT>malloc</TT> call.(In many cases,you'll free blocks of memory in the reverse order you allocated them,although this order is by no means required.)</p><p>See also question <a href="faqcatbafd.html?sec=malloc#freeb4exit">7.24</a>.<hr><hr><hr><a name="freeb4exit"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/freeb4exit.html"><!-- qtag -->Question 7.24</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>Must I free allocated memory before the program exits?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>You shouldn't have to.A real operating systemdefinitively reclaimsall memoryand other resourceswhen a program exits;the systemcannot affordto havememory integritydependon the whims of random programs.(Strictly speaking,it is not even <TT>free</TT>'s jobto return memory to the operating system;see question <a href="faqcatbafd.html?sec=malloc#freetoOS">7.25</a>.)Nevertheless, some personal computersare said not to reliably recover memoryunless it was freed before exiting,and all that can be inferred from the ANSI/ISO C Standardis that this is a ``quality of implementation issue.''</p><p>On the other hand,the C library <TT>free</TT> function rarely returns memory backto the operating system(see question <a href="faqcatbafd.html?sec=malloc#freetoOS">7.25</a>),so calling <TT>free</TT> probably isn't the way to guaranteethat an exiting program's memory is recovered by the system, anyway.</p><p>In any case,it can be considered good practice to explicitly free allmemory--forexample,in case the program is ever rewrittento perform its main task more than once(perhaps under a Graphical User Interface).<a href="../../malloc/prleak.html" rel=subdocument>[footnote]</a>On the other hand,there are programs(such as interpreters)that don't know whatmemorythey're done with(i.e. what memory could be freed)until it's time to exit,and since all memory should be released at exit,it would be a needless,potentiallyexpensive, anderror-prone exercisefor the program to explicitly free all of it.</p><p>Additional links:<a href="faqcatbafd.html?sec=malloc#freeb4exit2">further explanation</a></p><p>References:ISO Sec. 7.10.3.2<hr><hr><hr><a name="freetoOS"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../malloc/freetoOS.html"><!-- qtag -->Question 7.25</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I have a program which <TT>malloc</TT>sand later<TT>free</TT>s a lotof memory,butI can see from the operating systemthatmemory usagedoesn'tactuallygo back down.</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Mostimplementations of <TT>malloc</TT>/<TT>free</TT> do not return <TT>free</TT>d memoryto the operating system,but merely make it availablefor future <TT>malloc</TT> calls

⌨️ 快捷键说明

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