| <!-- CLIPPED FROM: http://www.embedded.com/columns/programmingpointers/200900195 --> <FONT size="3" face="Verdana" color="#003366">Using size_t appropriately can improve the portability, efficiency, or readability of your code. Maybe even all three.</FONT>
Numerous functions in the Standard C library accept arguments or return values that represent object sizes in bytes. For example, the lone argument in <FONT size="2" face="Courier">malloc(n)</FONT> specifies the size of the object to be allocated, and the last argument in <FONT size="2" face="Courier">memcpy(s1, s2, n)</FONT> specifies the size of the object to be copied. The return value of <FONT size="2" face="Courier">strlen(s)</FONT> yields the length of (the number of characters in) null-terminated character array s excluding the null character, which isn’t exactly the size of <FONT size="2" face="Courier">s</FONT>, but it’s in the ballpark.
You might reasonably expect these parameters and return types that represent sizes to be declared with type <FONT size="2" face="Courier">int</FONT> (possibly <FONT size="2" face="Courier">long</FONT> and/or <FONT size="2" face="Courier">unsigned</FONT>), but they aren’t. Rather, the C standard declares them as type <FONT size="2" face="Courier">size_t</FONT>. According to the standard, the declaration for <FONT size="2" face="Courier">malloc</FONT> should appear in <FONT size="2" face="Courier"><stdlib.h></FONT> as something equivalent to:
<FONT size="2" face="Courier">void *malloc(size_t n);</FONT>
|