1. 程式人生 > >memcpy 記憶體重疊問題

memcpy 記憶體重疊問題

凡是涉及cpy函式感覺都要考慮記憶體重疊問題,並且在重疊情況下考慮是前重疊 還是後重疊的情況來選擇*dest++=*source++  還是 *dest--=*source--來進行記憶體複製。

寫一個簡單的memcpy關於記憶體覆蓋的原始碼:

void   * memcpy(void * dest, void * source,size_t count)
{
	if(dest==NULL||source==NULL)
	{
		return NULL;
	}
	else
	{
		char * tmp_source,* tmp_dest;
		tmp_source=(char *)source;
		tmp_dest=(char *)dest;//if the pointer is string we must check the length of two string.
		if(dest + count >= source || source + count >= dest)//there are two kind of memory overlap
		{
			if(dest + count >= source)//dest is front of the source overlap
			{
				while(count--)
				{
					*tmp_dest++=*tmp_source++;
				}
			}
			else//dest is behind of the source overlap
			{
				tmp_dest+=count-1;
				tmp_source+=count-1;
				while(count--)
				{
					*tmp_dest--=*tmp_source--;
				}
			}
		}
		else//no overlap
		{
			while(count--)
			{
				*tmp_dest++=*tmp_source++;// *tmp_dest--=*tmp_source-- is also right
			}
		}
	}
	return(dest);//why return the pointer?? , it can nest use and if overlap we can creat new space to receive this pointer
}