Off-by-one error

A friend of mine asked for me to solve his bug, saying that he is suffering from it. You know, I am running my own site, Debuglab.com, and he posted the bug. When I read the problem statement, I could find off-by-one error.

HRESULT CFileUpload::_MultiToWideChar(PBYTE _pbytStartPos, PBYTE _pbytEndPos, LPWSTR &_pwszBuffer, LONG &_nLenOfBuffer)
{
  ...
  if(NULL == _pbytStartPos || NULL == _pbytEndPos)
  {
   _pwszBuffer = L"";
   hr = S_OK;;
   goto _FUNC_END;
  }

  bytTemp = *_pbytEndPos; //Exception

  *_pbytEndPos = '\0';
}

and the code calling that function is the following.

  if(FAILED(_MultiToWideChar(&vecFormData[0], &vecFormData[vecFormData.size()], pBuffer , nLenOfBuffer)))
  {
   goto _FUNC_END;
  }

Can you find a bug in this source immediately? I did. It took only 3 seconds. This is the traditional off-by-one error. If you are a C++ programmer, you know that every array's range is from 0 to n-1. But in this source the programmer ignored or missed the basic concept.

&vecFormData[vecFormData.size()]

I bet this code should be like the following code.

&vecFormData[vecFormData.size()-1]

 

Published Tue, Jun 7 2005 8:54 by Wooseok Seo
Filed under:

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Powered by Community Server (Commercial Edition), by Telligent Systems