Saturday 30 July 2016

Difference between size_t and ssize_t

Remember how typedef is used to give alternate names to data types and how this is done to add an extra layer of context to our variables? Of course you do, you seem very intelligent, almost a genius. 
Today I'll be presenting an example based on the very concept. Be sure not to miss out, it's as ubiquitous  in C as obesity is in Cities.

size_t is an alias for a 16 bit integer. It is unsigned in nature. How did this alias came to form? Via the following statement (as I'd like to think):

typedef unsigned int size_t;

What is the use case for this alias? Representing sizes of things in memory. It literally stands for size of type. So whenever you wish to store the size of some variable in another variable, make sure to have the second variable be of the type size_t. Yes, you can very well ignore this advice and have it be of unsigned int but doing so will make it clear for any one reading your code that what this variable is there for i.e. storing sizes of stuff. It's not an overhead. You don't have to worry about writing the above line of code to be able to use this alias. It has been done for you and comes as part of the C language. This fact shall come as a ringing endorsement for the legitimacy of the size_t type. In fact, the famously used sizeof operator in C has been defined as returning the type size_t. Why? well because it returns the size of something.

ssize_t is an alias for a 16 bit signed integer. This means that it can even take negative values. It exists due to some statement buried deep in C, similar to the following one:

typedef int ssize_t;

This alias is used in cases where there is a chance of a failure in memory allocation. But first back up a bit. When you assign some amount of memory to a pointer, then this can either result in your pointer getting the requested amount of memory or a failure of your request and no memory being allocated. In the former (preferred) case, the allocated memory (in bytes) is returned using ssize_t type. If the allocation fails then a negative number is returned, which is again done using the ssize_t type as it can hold negative values as well.

You're definitely a genius now. It's pandemic. 

3 comments:

  1. Lots of incorrect information here, sadly. size_t and ssize_t are not guaranteed to be 16-bit values, and indeed are unlikely to be. Even if they were typedef'd as you indicate, which again they're not guaranteed to be, int is not 16-bit type on any 32-bit or 64-bit platform I've ever encountered. Also note that size_t is standard C, ssize_t is POSIX so may not be available cross-platform.

    ReplyDelete
  2. Thanks @cooperised - I was shocked that this entirely wrong article showed up among the first search results for ssize_t :-o

    ReplyDelete
  3. Thank you. I am reading in while in a quarantine. I try to find a good hash function for my data structure.

    ReplyDelete