Learn memory functions in 10 minutes: usage and simulation implementation of memcpy, memmove, memset, memcmp.

Table of Contents: Memory Operation Functions

1: memcpy function (memory copy)

2: memmove function (memory copy)

Three: memset function (memory setting)

Four: memcmp function (memory comparison )

1: memcpy function

Implementation principle of memcpy memory function:                                                                                                     

Copy num bytes of data from the location pointed to by source to the memory block pointed by destination. This function will not stop when encountering 0' .

Therefore, three parameters need to be passed in to the memcpy function, namely the first address of the target memory space, the first address of the copied memory space and the number of bytes copied.

 The memcpy function can copy string data, integer array data, structure data and many other types..., but because the memcpy memory function cannot copy itself, the memcpy function cannot copy data in the memory overlap area, so there are certain limitations, here, Xiaoxia recommends that you apply the following memmove function when encountering data copy to perfectly avoid all unstable factors.

2: memmove function

The implementation principle of the memmove memory function (it can be used even if there is overlap in the memory ): 

Used to copy memory data. If the target area and the source area overlap,
memmove can ensure that the bytes of the overlapping area are copied to the target area before the source string is overwritten ,
but the source content will be changed after copying. But when the target area does not overlap with the source area, it has the same function as the memcpy function.

The memmove function implements the overlapping memory process:

 In summary, there are three situations when encountering memory overlap:

1. Copy from front to back (there is overlap in the memory space) -> If the address of the source is higher than the address of disnation: perform regular assignment, and copy the address of disnation backwards from the address of source until the number of bytes copied Size_t num is reached, and the copy is completed.

2. Copy from back to front (there is overlap in the memory space) -> If the address of the source is lower than the address of disnation: perform assignment in reverse order, and copy the address of disnation+num from the address of source+num forward until the copy The number of bytes reaches size_t num, and the copy is completed.

3. You can copy from front to back or from back to front (there is no overlap in memory space) .

 Simulate the implementation of the memmove function:

We can write a my_memmove function ourselves to simulate the function of memmove function

First define the function void* my_memmove(void* s1, const void* s2, size_t len)

Because memmove is a function that copies memory, there is no restriction on the data type that is copied in the memory, so the parameter data type passed in is void*, and the return value is also an untyped address.

size_len is an unsigned integer type, indicating the number of bytes we want to copy, so inside the my_memmove function, we can write like this

#include<stdio.h>
#include<assert.h>
void* my_memmove(void* s1, const void* s2, size_t len)
{
	assert(s1);
	assert(s2);
	void* ret = s1;
	int i = 0;
	
	if (((char*)s2)>((char*)s1))//从s2的前端依次拷贝
	{
		for(i=0;i<len;i++)
		{
			*((char*)s1) = *((char*)s2);
			(char*)s1 = (char*)s1 + 1;
			(char*)s2 = (char*)s2 + 1;
		}
	}
	else
	{
		while (len--)//从s2的后端开始拷贝
			{
				*((char*)s1 + len) = *((char*)s2 + len);
			}
	}

	return ret;
}
int main()
{
	
	int arr[20] = { 0 };
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		arr[i] = i + 1;
	}
	my_memmove(arr + 1, arr , sizeof(int) * 5);
	for (i = 0; arr[i] != 0; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

Three: memset function

The implementation principle of memset memory function: num bytes initialize the memory block 

Assign the value of value from the ptr address to the memory space of size_t num bytes backward .

Function definition of memset:

Simulate the implementation of the memset function:

We can write a my_memset function ourselves to simulate the functions of the memset function

First define the function void* my_memset(void * ptr, int value, size_t num)

Because memset is a function that copies memory, there is no restriction on the data type that is copied in the memory, so the parameter data type passed in is void*, and the return value is also an untyped address.

size_num is an unsigned integer type, indicating the number of bytes we want to assign, so inside the my_memset function, we can write like this

#include<stdio.h>
void* my_memset(void* ptr, int value, size_t num)
{
	while (num--)
	{
		*((char*)ptr) = value + '0';
		ptr = (char*)ptr + 1;
	}
}
int main()
{
	char arr[] = "abcdefghijk";
	my_memset(arr+1, 6, 3);
	printf("进过赋值后的结果->%s\n", arr);
	return 0;
}

A small knowledge point in the simulation implementation of the memset function is: how to convert numbers into characters. The ASCLL value of the character '0' is 48, and the ASCLL value of the number 0 is 0, so add the number to the character '0' ' to get the corresponding characters .

The result of this function is:

Four: memcmp function

The implementation principle of memcmp memory function: used to compare the first N bytes of memory

The comparison of string sizes is determined by the order in the ASCII code table, and the order is also the value of the characters. memcmp() first subtracts the first character value of s2 from the first character value of s1. If the difference is 0, it will continue to compare the next character. If the difference value is not 0, the difference value will be returned.

If the contents of the two strings are exactly the same, 0 is returned;

If S1 is greater than S2, then it is greater than 0,

Otherwise, it is less than 0;

The function definition of memcmp: compare size_t num bytes from the ptr1 memory space and the ptr2 memory space in sequence, and the const modification of per1 and ptr2 cannot change their contents.

Simulate the implementation of memcmp function:

We can write a my_mecmp function ourselves to simulate the functions of the memcmp function

First define the function void* my_memcmp(const void*ptr1,const void*ptr2,size_t num)

#include<stdio.h>
void* my_memcmp(const void* ptr1, const void* ptr2, size_t num)
{
	while (num--)
	{
		if (*(char*)ptr1 == *(char*)ptr2)
		{
			ptr1 = (char*)ptr1 + 1;
			ptr2 = (char*)ptr2 + 1;
		}
		else
		{
			return *(char*)ptr1 - *(char*)ptr2;
		}
	}
}
int main()
{
	char s1[] = "abcd456ef";
	char s2[] = "abef789nmn";
	int ret=my_memcmp(s1, s2, 5);
	printf("差值为->%d", ret);

	return 0;
}

The execution result is:

Results of the:

my_memcmp(s1+7, s2,5):1 //String s1>String s2, return positive value

my_memcmp(s1, s2,5):-1 // String s1<String s2, return negative value

my_memcmp(s1, s2,2):0 //String s1=String s2, return 0

If you think the article is good, I look forward to your one-click triple link. Your encouragement is the source of motivation for my creation. Let's work hard together and see you at the top! ! !

Guess you like

Origin blog.csdn.net/smile_sundays/article/details/131859452