C language - simulate memcpy, memmove

1. Introduction and implementation of memcpy function

The function memcpy copies num bytes of data backwards from the location of source to the memory location of destination. The function does not stop when it encounters '\0'. If the source and destination overlap in any way, the result of the copy is undefined.

void * memcpy ( void * destination, const void * source, size_t num );

In fact, it is very simple to implement memcpy. No matter what data type is passed in, we will uniformly convert it to char*. We know that the char data type occupies one byte. We can understand it as a minimum unit, no matter what data Type we copy byte by byte. The code is implemented as follows:

void* my_memcpy(void* dest, const void* src, size_t num)
{
	void* ret = dest;

	while (num--)
	{
		*(char*)dest = *(char*)src;
		dest = (char*)dest + 1;//逐个字节++
		src = (char*)src + 1;//逐个字节++
	}
	return ret;
}

2. Introduction and implementation of memmove function

The difference with memcpy is that the source memory block and target memory block processed by the memmove function can overlap. If the source space and the target space overlap, you have to use the memmove function to deal with it.

void * memmove ( void* destination, const void * source, size_t num );

Here we will discuss destinantion > source and destinantion < source in two cases. Let’s first look at the code implementation:

void* my_memmove(void* dest, const void* src, size_t num)
{
	void* ret = dest;

	if (dest < src)
	{
		//前->后
		while (num--)
		{
			*(char*)dest = *(char*)src;
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}
	else
	{
		//后->前
		while (num--)//20
		{
			*((char*)dest + num) = *((char*)src + num);
		}
	}
	return ret;
}

Note that when dest<src is the same as the memcpy implementation code, because copying from front to back here will not change the value of the overlapping part.

The above is the entire implementation process and ideas of memcpy and memmove, thank you for watching.

Guess you like

Origin blog.csdn.net/m0_74358683/article/details/131678525