strcpy和strnpy源码实现及缺点

  • strcpy源码如下:
char * strcpy ( char * destination, const char * source )
{
	if (destination==NULL || source ==NULL)
	{
		throw "pointer error";
	}
	char * pTemp = destination;
	while((*destination++ = *source++) != '\0');
	return pTemp;
}
  • strcpy最大的缺点在于其使用循环while((*destination++ = *source++) != ‘\0’);进行复制时,是以结束符’\0’为判断结束标志的。也就是说,如果destination所指的存储空间不够大的话,这个函数会将source 中的部分内容拷贝到destination所指内存空间后面的内存中。而destination所指空间后面的内存却是不可知的,有可能已经被其他资源占用了,这样就会破坏原先存储的内容,导致系统崩溃。
  • strncpy源码如下:
char * strncpy ( char * destination, const char * source, size_t num )
{
	if (destination==NULL || source ==NULL)
	{
		throw "pointer error";
	}
	char * pTemp = destination;
	while((*destination++ = *source++) && num)
		num--;
	if(num)
	{
		while (num--)
			*destination++ = '\0';
	}
	return pTemp;
}
  • strncpy相对于strcpy的优点在于其增加了一个参数num来控制拷贝的长度。但是strncpy仍没有改变strcpy的缺点,即在count的长度大于destination内存长度时,仍需占用其后的内存。另外,strncpy在count大于source的长度时,会在其后补’\0’,这样有时就会造成无效的内存占用,浪费空间。

猜你喜欢

转载自blog.csdn.net/lianggx6/article/details/88014588