Pikir dan Rasa

cogito ergo sum

Why size_t matters by Dan Saks [an excerpt]

leave a comment »

Dan Saks

7/3/2007 12:27 PM EDT

Using size_t appropriately can improve the portability, efficiency, or readability of your cod.  Maybe even all three.


Numerous functions in the Standard C library accept arguments or return values that represent object sizes in bytes. For example, the lone argument in malloc(n) specifies the size of the object to be allocated, and the last argument in memcpy(s1, s2, n) specifies the size of the object to be copied. The return value of strlen(s) 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 s, but it’s in the ballpark.


You might reasonably expect these parameters and return types that represent sizes to be declared with type int (possibly long and/or unsigned), but they aren’t. Rather, the C standard declares them as type size_t. According to the standard, the declaration for malloc should appear in <stdlib.h> as something equivalent to:

void *malloc (size_t  n);


and the declarations for memcpy and strlen should appear in <string.h> looking much like:

void  *memcpy (void *s1, void const  *s2, size_t  n);  size_t  strlen (char const *s);



The type size_t also appears throughout the C++ standard library. In addition, the C++ library uses a related symbol size_type, possibly even more than it uses size_t.


In my experience, most C and C++ programmers are aware that the standard libraries use size_t, but they really don’t know what size_t represents or why the libraries use size_t as they do. Moreover, they don’t know if and when they should use size_t themselves.


In this column, I’ll explain what size_t is, why it exists, and how you should use it in your code.

via Why size_t matters.

Written by sunupradana

February 16, 2012 at 11:15 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: