Search code examples
c++cstrcpy

strcpy... want to replace with strcpy_mine which will strncpy and null terminate


The clue is in the title but basically I've inherited some code which has 800+ instances of strcpy. I want to write a new function and then to replace strcpy with strcpy_mine.

So I'm trying to work out what parameter list strcpy_mine will have.

I tried:

void strcpy_mine( char* pTarget, const char* const pCopyMe )
{
  const unsigned int lenAlwaysFour = sizeof(pCopyMe ); //:(
  strncpy( pTarget, pCopyMe, lenAlwaysFour );

  //add extra terminator in case of overrun
  pTarget[lenAlwaysFour] = 0;
}

but the sizeof is always 4 pCopyMe is a pointer

what I don't want to do is replace

strcpy (buf, pCopyMe);

with

strncpy (buf, pCopyMe, sizeof(pCopyMe)); buf[sizeof(pCopyMe)] = 0;

Any ideas? (strcpy_l isn't available)


Solution

  • Depending on how the call-sites look like, often majority of cases can be handled by a simple template:

    #include <string.h>
    
    template <int bufferSize>
    void strcpy_mine( char (&pTarget)[bufferSize], const char* const pCopyMe )
    {
      strncpy( pTarget, pCopyMe, bufferSize-1 );
    
      //add extra terminator in case of overrun
      pTarget[bufferSize-1] = 0;
    }
    
    int main()
    {
      char buf[128];
      strcpy_mine(buf,"Testing");
      return 0;
    }
    

    If you are using Microsoft Visual Studio 2005 or newer, see Secure Template Overloads for a Microsoft implementation.