Working code isn't necessarily bug free

There is always a perception that a working code is considered very stable and free of bugs. Quite a few decisions like estimation for a new feature, estimation for resources to support that code are taken merely based on that very illusion. I happened to work on one issue, which proves otherwise,

encoding_library(void *ptr, unsigned int length)
{
// Parameter check
// ptr points to a chunk of memory supposed to have encoded data
// Invoke a function to perform a part of the encoding
encode_partial(ptr, &length);
// Invoke another function to continue encoding on the same buffer
encode_complete(ptr, &length);
}


encode_partial(void *ptr, unsigned int* length)
{
// This function fills the buffer with the encoded data and as and when the memory of buffer is finished, it passes the memory to the caller and requests for a new chunk of memory. This happens until the encoding corresponding to this function is finished...
}

encode_complete(void *ptr, unsigned int* length)
{
// Finishes the encoding and conveys the same to the caller.
}

It is anyone's guess that encode_partial should have accepted a pointer to the pointer type, as the location where the ptr is pointing to, is being changed in the function and the same should be passed to the parent function. However, the above code was working fine without any segmentation fault... I was puzzled initially, it didn't make any sense at all...

Finally i realized that the new chunk of memory allocated happened to be at the exact same address as that of the previous chunk, and thats height of coincidence. This code was working on ARM processor with VRTX (Versatile real time executive operating system). It might have crashed had it been ported to some other platform or for that matter, when the memory allocation library of the current platform were to be modified.

Best way to avoid such bugs is probably a proper code walk through.

No comments: