9 Jun 2008 salimma   » (Apprentice)

C types 101


I was cleaning up the code of an application that I’m packaging for Fedora, and was Googling for information on size_t (in the code, a size_t variable was being printed as a normal integer (%d), which triggered a compiler warning, and I forgot what the relevant option is. Ended up finding it in printf’s manpage) when I discovered this rather well-written gem.
clipped from www.embedded.com
<!-- 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>
  blog it

Syndicated 2008-06-09 01:12:17 from Intuitionistically Uncertain ยป Technology

Latest blog entries     Older blog entries

New Advogato Features

FOAF updates: Trust rankings are now exported, making the data available to other users and websites. An external FOAF URI has been added, allowing users to link to an additional FOAF file.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!