6/17/2008

06-17-08 - 2

strncpy is one of those basic functions that doesn't do what you want. If you use it like this, as most people do :
char buf[256];
strncpy(buf,from_str,256);
You just wrote buggy code. If from_str is actually longer than 256, buf will not have a null and when you try to use it as a string it will hose you.

The way I like to replace library functions now is with a namespace and a using :

namespace my_strncpy
{

	inline void strncpy(char * to,const char *fm,int count)
	{
		::strncpy(to,fm,count);
		to[count-1] = 0;
	}

}

using namespace my_strncpy;
Any code that follows this and calls "strncpy" will actually call my_strncpy::strncpy

No comments:

old rants