Writing portable code

25 07 2008

I just wanted to share a problem that I have come across today when I was at work. This post is about writing portable code. To give you an example, here is the problem that I have faced, look at this code snippet in C.

someBuf = (SomeType *) malloc(length);

if (someBuf)
{
someBuf->someVar = x;
}

In the above statement, there is no check to know the validity of the length. It occurred to me that the value of the length was “0″. The C standard (ISO/IEC 9899) says,

If the size of the space requested is zero, the behavior is implementation-defined:

Either a null pointer is returned
Or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

In my case, the malloc returned an address(zero sized buffer), the validation on the allotted buffer was successful because someBuf was not NULLĀ  and eventually the program core dumped since the code followed the above statement accessed object (object of size zero?). So the point I would like to make here is, it’s better to write our own wrapper functions that would make the behavior consistent across different implementations.