📄 faqcatbafd.html
字号:
Have you<TT>#include</TT>d <TT><stdlib.h></TT>,or otherwise arrangedfor<TT>malloc</TT>to be declared properly?If not,the compiler assumes thatit returnsan<TT>int</TT>(seequestion <a href="faqcatd3c2.html?sec=decl#implfdecl">1.25</a>),which is not correct.(The same problem could arise for <TT>calloc</TT> or <TT>realloc</TT>.)See also question <a href="faqcatbafd.html?sec=malloc#sizetlong">7.15</a>.</p><p>References:H&S Sec. 4.7 p. 101<hr><hr><hr><a name="cast"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/cast.html"><!-- qtag -->Question 7.7</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>Why does some code carefully cast the values returned by <TT>malloc</TT>to the pointer type being allocated?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Before ANSI/ISOStandardCintroducedthe <TT>void *</TT> generic pointer type,these casts weretypicallyrequiredto silencewarnings(and perhaps induce conversions)when assigningbetween incompatible pointer types.</p><p>Under ANSI/ISO Standard C,these casts areno longer necessary.It can also be arguedthattheyarenowto be discouraged;see question <a href="faqcatbafd.html?sec=malloc#mallocnocast">7.7b</a>.Furthermore,well-defined,low-riskimplicit conversions(such as those which C has always performed betweeninteger and floating-point types)can be considered afeature.</p><p>On the other hand,some programmers prefer to make <em>every</em> conversion explicit,to record that they have considered each caseand decided exactly what should happen(see also question <a href="faqcataae2.html?sec=style#voidcasts">17.5</a>).Also,the casts are typically seen in C codewhichfor one reason or anotheris intended to be compatible with C++,where explicit castsfrom<TT>void *</TT>are required.</p><p>(By the way, the language in sections 6.5 and 7.8.5 ofK&R2which suggests that the casts are requiredis ``overenthusiastic.'')</p><p>To some extent,whether you use these casts or not is a matter of style;seesection<a href="faqcataae2.html?sec=style#index">17</a>.</p><p></p><p>Additional links:<a href="../../malloc/sd3.html" rel=subdocument>further explanation by Mark Brader</a></p><p>References:H&S Sec. 16.1 pp. 386-7<hr><hr><hr><a name="mallocnocast"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/mallocnocast.html"><!-- qtag -->Question 7.7b</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What's wrong with casting <TT>malloc</TT>'s return value?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Suppose that youcall <TT>malloc</TT>but forget to <TT>#include <stdlib.h></TT>.The compiler is likely to assume that <TT>malloc</TT>is a function returning <TT>int</TT>,which is of course incorrect, and will lead to trouble.Now, ifyour call to <TT>malloc</TT> is of the form<pre> char *p = malloc(10);</pre>the compiler will noticethat you're seemingly assigning an integer to a pointer,and will likely emit a warning of the form``assignment of pointer from integer lacks a cast''(see question <a href="faqcatbafd.html?sec=malloc#decl">7.6</a>),which will alert you to the problem.(The problem is of course that you forgot to <TT>#include <stdlib.h></TT>,not that you forgot to use a cast.)If, on the other hand, your call to <TT>malloc</TT>includes a cast:<pre> char *p = (char *)malloc(10);</pre>the compiler is likely to assume that you know what you're doing,that you really do want to convert the <TT>int</TT> returned by<TT>malloc</TT> to a pointer, and the compilertherefore probably <em>won't</em> warn you.But of course <TT>malloc</TT> does not return an <TT>int</TT>,so trying to convert the <TT>int</TT> that it doesn't returnto a pointer is likely to lead to a different kind of trouble,which will be harder to track down.</p><p>(Of course, compilers are increasingly likely--especially under C99--toemit warnings whenever functions are called without prototypes in scope,and such a warning would alert you to the lack of <TT><stdlib.h></TT>whether casts were used or not.)<hr><hr><hr><a name="mallocnocast2"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/mallocnocast2.html"><!-- qtag -->Question 7.7c</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>In a call to <TT>malloc</TT>,what does an error like``Cannot convert `<TT>void *</TT>' to `<TT>int *'''mean?</TT></p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>It means you're using a C++ compilerinstead of a C compiler.See question <a href="faqcatbafd.html?sec=malloc#cast">7.7</a>.<hr><hr><hr><a name="sizeofchar"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/sizeofchar.html"><!-- qtag -->Question 7.8</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I see code like<pre> char *p = malloc(strlen(s) + 1); strcpy(p, s);</pre>Shouldn't that be <TT>malloc((strlen(s) + 1) * sizeof(char))</TT>?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>It's never necessary to multiply by <TT>sizeof(char)</TT>,since<TT>sizeof(char)</TT> is, by definition, exactly 1.(On the otherhand,multiplying by <TT>sizeof(char)</TT> doesn't hurt,andin some circumstancesmay help byintroducing a <TT>size_t</TT> into the expression;see question <a href="faqcatbafd.html?sec=malloc#sizetlong">7.15</a>.)See alsoquestions <a href="faqcate107.html?sec=charstring#sizeofchar">8.9</a> and <a href="faqcate107.html?sec=charstring#wchar">8.10</a>.</p><p>References:ISO Sec. 6.3.3.4<br>H&S Sec. 7.5.2 p. 195<hr><hr><hr><a name="mymallocretp"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/mymallocretp.html"><!-- qtag -->Question 7.9</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I wrote a little wrapper around <TT>malloc</TT>,but it doesn't work:<pre> #include <stdio.h> #include <stdlib.h> mymalloc(void *retp, size_t size) { retp = malloc(size); if(retp == NULL) { fprintf(stderr, "out of memory\n"); exit(EXIT_FAILURE); } }</pre></p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>See question <a href="faqcatabdc.html?sec=ptrs#passptrinit">4.8</a>.(In this case, you'll want tohave <TT>mymalloc</TT> return the <TT>malloc</TT>'ed pointer.)<hr><hr><hr><a name="mimic3"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/mimic3.html"><!-- qtag -->Question 7.10</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I'm trying to declare a pointer and allocate some space for it,but it'snot working.What's wrong withthis code?<pre>char *p;*p = malloc(10);</pre></p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>See question <a href="faqcatabdc.html?sec=ptrs#mimic">4.2</a>.<hr><hr><hr><a name="fcninit2"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/fcninit2.html"><!-- qtag -->Question 7.10a</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What's wrong withthis initialization?<pre>char *p = malloc(10);</pre>My compiler is complaining aboutan ``invalid initializer'',or something.</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>See question <a href="faqcatd3c2.html?sec=decl#fcninit">1.31b</a>.<hr><hr><hr><a name="lintpalign2"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/lintpalign2.html"><!-- qtag -->Question 7.10b</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How can I shut off the``warning: possible pointer alignment problem''messagewhich<TT>lint</TT> gives me for each call to <TT>malloc</TT>?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>See question <a href="faqcatccbd.html?sec=resources#lintptralign">18.5</a>.<hr><hr><hr><a name="dynarray2"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/dynarray2.html"><!-- qtag -->Question 7.11</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How can I dynamically allocate arrays?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>See questions <a href="faqcatca65.html?sec=aryptr#dynarray">6.14</a>and <a href="faqcatca65.html?sec=aryptr#dynmuldimary">6.16</a>.<hr><hr><hr><a name="memavail2"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/memavail2.html"><!-- qtag -->Question 7.12</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How can I find out how much memory is available?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>See question <a href="faqcatea63.html?sec=osdep#memavail">19.22</a>.<hr><hr><hr><a name="malloc0xref"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/malloc0xref.html"><!-- qtag -->Question 7.13</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What should <TT>malloc(0)</TT> do?Return a null pointer or a pointer to 0 bytes?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>See question <a href="faqcat7d4b.html?sec=ansi#malloc0">11.26</a>.<hr><hr><hr><a name="lazyalloc"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/lazyalloc.html"><!-- qtag -->Question 7.14</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I've heard that some operating systemsdon't actually allocate <TT>malloc</TT>'ed memoryuntiltheprogram tries touseit.Is this legal?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>It's hard to say.The Standard doesn't say that systems can act this way,but it doesn'texplicitlysay that they can't, either.(Such a ``deferred failure'' implementationwould not seem to conform to the implied requirements of the Standard.)</p><p>Theconspicuousproblem is that,by the timethe program gets around to trying to use the memory,there might not be any.Theprogramin this case must typically be killed by the operating system,since the semantics of C provide no recourse.(Obviously,<TT>malloc</TT> is supposed to return a null pointerif there's no memory,so that the program--aslong as it checks <TT>malloc</TT>'s return value at all--nevertries to use more memory than is available.)</p><p>Systems thatdo this ``lazy allocation''usually provide extra signalsindicating that memory is dangerously low,but portable or naïve programs won't catch them.Some systems that do lazy allocationalso provide a way to turn it off(reverting to traditional <TT>malloc</TT> semantics),on a per-process or per-user basis,but the details vary from system to system.</p><p>Additional links:A<a href="faqcatbafd.html?sec=malloc#lazyalloc2">longer explanation</a>of the tradeoffs concerning ``lazy allocation''</p><p>References:ISO Sec. 7.10.3<hr><hr><hr><a name="sizetlong"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/sizetlong.html"><!-- qtag -->Question 7.15</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font><TT>malloc</TT>isreturning crazy pointer values,but I <em>did</em> read question <a href="faqcatbafd.html?sec=malloc#decl">7.6</a>and I have included the line<pre> extern void *malloc();</pre>before I call it.</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font><TT>malloc</TT> accepts an argument of type <TT>size_t</TT>,and <TT>size_t</TT> may bedefinedas<TT>unsigned long</TT>.If you are passing <TT>int</TT>s(or even <TT>unsigned int</TT>s),<TT>malloc</TT> may be receiving garbage(orsimilarlyif you are passing a <TT>long</TT> but <TT>size_t</TT> is<TT>int</TT>).</p><p>In general,it is much, much saferto declare standard library functionsby #including the appropriate header files,rather than typing <TT>extern</TT> declarations yourself.See also question <a href="faqcatbafd.html?sec=malloc#sizewrap">7.16</a>.</p><p>(A related problem is that it is not safe to print <TT>size_t</TT> values,including the result of <TT>sizeof</TT>,using <TT>printf</TT>'s <TT>%d</TT> format.The portable approachis to use an explicit <TT>(unsigned long)</TT> cast,and <TT>%lu</TT> format:<TT>printf("%lu\n", (unsigned long)sizeof(int))</TT>.See also question <a href="faqcat744e.html?sec=varargs#proto2">15.3</a>.)</p><p>References:ISO Sec. 7.1.6, Sec. 7.1.7<hr><hr><hr><a name="sizewrap"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../malloc/sizewrap.html"><!-- qtag -->Question 7.16</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I'm allocating a large array for some numeric work,using the line<pre> double *array = malloc(300 * 300 * sizeof(double));</pre><TT>malloc</TT> isn't returning null,butthe program is acting strangely,as if it's overwriting memory,or <TT>malloc</TT> isn't allocating as much as I asked for,or something.</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Notice that 300 x 300 is 90,000,which will not fit in a 16-bit <TT>int</TT>,
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -