Search This Blog

Wednesday, October 30, 2013

Some simple change to prevent future problem

This sounds so basic but I think we always want to have a second look on our code to see if we can improve the code. For instance, I had a piece of code that takes index as input and return the value from the array. The following is hypothetical example.

 int map_func(ULONG index)  
 {  
   assert(index < max);  
   return array[index];  
 }  

When I call this function, I make sure that index is within the range. But my code interfaces with other code and as the time goes on, the code becomes pretty complicated that I had a case where input 'index' was out of range and hence, the program crashed.
So I fixed that and after a few months later, the similar issue occurred. Only then, I realized that I should have changed 'assert' to the check that would survive even in free build.
Here is the new change.
 int map_func(ULONG index)  
 {  
   if (index >= max) {  
     assert(FALSE);  
     log("error occurred: %d\n", index);  
     return -1;  
   }  
   return array[index];  
 }  

Now, I can avoid program crash in free build and also have the assert in checked build. I know this is such a simple case but I only came up with this resolution when I stopped and thought about the fix one more time.

I think I will need this stop and think moment for all my works.