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.



3 responses

25 07 2008
Anders Sandvig

I’m not sure why you’re trying allocate buffers of zero length, but I guess something like this would solve it:

#define MALLOC(x) (x > 0 ? malloc(x) : 0)

25 07 2008

@Anders I was not actually trying to allocate buffer of zero length, the value that was passed to the malloc was given at run-time, and my fellow colleagues did not check value and directly passed to the malloc . And what I meant my writing wrappers is that exactly what you have mentioned as a macro, or a function that validates the passed value.

28 07 2008
Anders Sandvig

Yeah, I see. In general I would say that such data should be validated before being sent to malloc(), as there could also be other illegal values (i.e. trying to allocate too much memory). I consider the macro somewhat of a hack, just to avoid crashes, but it shouldn’t be an excuse not to validate data🙂

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: