Friday, April 5, 2013

size_t is not unsigned int !!

I always consider size_t is just a typedef of unsigned int and that drops me to the torment today for hours. 

The thing I am trying to do is simple. It's a socket write and read. 

write:
...
size_t length = _value.size();

boost::asio::write(*sock, boost::asio::buffer((const char*)&length, sizeof(length)));
...

read:
...
int length = -1;

boost::asio::read(*sock,
            boost::asio::buffer(&length, sizeof(length)));
...

And this bit of code stirs up the whole program. 

After hours of probing around, I happened to find out the issue is caused by with size_t. Because its size is different from int on the receiver end.

Here is the nice explanation from wiki:

The C language provides the separate types size_t and ptrdiff_t to represent memory-related quantities. Existing types were deemed insufficient, because their size is defined according to the target processor's arithmetic capabilities, not the memory capabilities, such as available address space. Both of these types are defined in the stddef.h header (cstddef header in C++).
size_t is used to represent the size of any object (including arrays) in the particular implementation. It is used as the return type of the sizeof operator. The maximum size of size_t is provided via SIZE_MAX, a macro constant which is defined in the stdint.h header (cstdint header in C++). It is guaranteed to be at least 65535.

It's clearly said size_t is platform dependant. Cool, it's portable. With a small program, I found size_t is 8 bytes on my machine, and int is 4.

More info for size_t here : http://www.embedded.com/electronics-blogs/programming-pointers/4026076/Why-size-t-matters  Altougth I haven't read it, could be interesting.

fun!fun!fun!

No comments:

Post a Comment