Simulation of string and memory library functions in C language

preface

C language has built-in quite a number of functions for users to use. These functions are integrated and encapsulated in the standard library. Users only need to call to complete the corresponding specific functions. These functions are called library functions.

The following are the relevant definitions given in Baidu Encyclopedia:

Library functions generally refer to functions that can be called by the compiler in C source program. For copyright reasons, the source code of the library function is generally invisible, but you can see its external interface in the header file.

------ Baidu Encyclopedia

The main content of this paper is to introduce the use of a series of library functions related to string and memory and their self implementation, so that readers can have a deeper understanding of the internal implementation mechanism of library functions.

Library functions related to strings

Library function strlen

The strlen function is used to calculate the length (in bytes) of a string. The following is the relevant function information given on the C and C + + official websites:

Use of strlen function

Let's call this function through a small case.

It can be seen from the running results that the string length calculated by the library function is 6 bytes, that is, the size occupied by the 6 characters abcdef. Let's take another example to compare it:

The result is shocking. How did this 16 come from? This array only contains 6 characters. The following points should be paid attention to when using this function:

  • strlen calculates the length of a string and returns the length of the string;

  • The actual parameter must be the address of the first element and received as a pointer;

  • The pointer traverses from front to back until \ 0 is found to calculate the size of the string.

    Based on the above analysis and combined with the case, we find that the array in case 2 does not have \ 0, that is, the calculation result is a random value, and the return value has no reference significance.

Simulation Implementation of strlen function

Through the previous use and analysis, we can write our own code to simulate and implement the basic functions of strlen function.

#include <stdio.h>

size_t my_strlen(char* str)
{
	size_t count = 0;  //This variable is used to count the number of characters

	while (*str)
	{
		count++;
		str++;
	}

	return count;
}
int main()
{
	char arr[] = "abcdefg";
	int r = my_strlen(arr);

	printf("character string arr The length of the is:%u\n", r);

	return 0;
}

The following figure shows its implementation details:

Starting from the address of the first element, if its content is not the character \ 0, the value of the counter will increase by 1, and the pointer will move backward by 1 byte until the pointer points to the address where the saved value is \ 0 to end the cycle. The value of the current counter represents the total length of the string.

Library function strcpy

strcpy is a library function that implements the string copy function. The following is the information given on the C and C + + official websites:

Use of strcpy function

Let's call this function through a small case.

From the result of calling this function, the content of arr1 has changed, and its value has become the content of arr2. Here are some features of this function:

  • The strcpy function copies the source string to the target string;
  • The end flag \ 0 of the source string will also be copied to the destination string;
  • After copying, the length of the target string will change, equal to the length of the source string;
  • The space of the target string should be large enough.

Simulation Implementation of strcpy function

Through the previous use and analysis, we can write our own code to simulate the basic functions of strcpy function.

#include <stdio.h>

char* my_strcpy(char* dest, char* src)
{
	char* ret = dest;    //Record the starting address of the target string
	while (*dest++ = *src++)
	{
		;        //Copy the contents of the source string to the destination string
	}

	return ret;
}

int main()
{
	char arr1[] = "abcd";
	char arr2[] = "ijk";
	printf("Before copying: %s", arr1);

	my_strcpy(arr1, arr2);

	printf("\n After copying: %s", arr1);


	return 0;
}

The following figure shows its implementation details:

dest pointer points to the starting position of the target string, src pointer points to the starting position of the source string, and the pointer moves back 1 byte after each character is copied. Copy all contents in the source string to the target string. When \ 0 is copied, the whole copy process is ended.

Library function strcmp

strcpy is a library function that implements string comparison. The following is the information given on the C and C + + official websites:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8dp2wral-1632012230846) (D: \ typera file \ self implemented image of library function related to string and memory \ 8.png)]

Use of strcmp

Let's call this function through a small case.

The following are the features of this function:

  • strcmp function realizes the comparison function of two strings;
  • The comparison starts from the first character. When the value of the corresponding position of the first string is equal to the second string, the two strings are equal, otherwise they are not equal;
  • The return value of the function is one of three cases: equal to 0, greater than 0 and less than 0.

Simulation Implementation of strcmp function

Through the previous use and analysis, we can write our own code to simulate the basic functions of strcmp function.

#include <stdio.h>

int my_strcmp(char* str1, char* str2)
{
	
	while (*str1 == *str2 && *str1 != '\0')
	{
		str1++;
		str2++;
	}

	if (*str1 == '\0' &&  *str2 == '\0')
	{
		return 0;   //The return value is equal to 0 and the two strings are equal
	}

	return (*str1 - *str2);  // The return value is greater than 0 or less than 0
}

int main()
{
	char arr1[] = "abc";
	char arr2[] = "abd";

	int r = my_strcmp(arr1, arr2);
	if (r == 0)
	{
		printf("arr1 be equal to arr2\n");
	}
	else
	{
		printf("arr1 Not equal to arr2\n");
	}
}

The following figure shows its implementation details:

str1 points to the first element address of the first string and str2 points to the first element address of the second string. If the corresponding position data is the same, move the two pointers backward. Once the corresponding data is found to be unequal, the cycle ends and returns the difference of ASCII codes at this time; If the corresponding data is still equal when traversing from the beginning to the end of the string, it indicates that the two strings are equal, and 0 is returned.

Library function strcat

strcat is a library function that implements the string append function. The following is the information given on the C and C + + official websites:

Use of strcat function

Let's call this function through a small case.

The following are the features of this function:

  • The strcat function appends a string at the end of the target string;
  • The start position of the append is \ 0 of the target string;
  • The \ 0 of the source string will also be appended to the target string to become the end flag of the target string;
  • The target string should be large enough.

Simulation Implementation of strcat function

Through the previous use and analysis, we can write our own code to simulate and realize the basic functions of strcat function.

#include <stdio.h>

char* my_strcat(char* dest, char* src)
{
	char* ret = dest;   //The address where the target string is saved

	while (*dest)
	{
		dest++;        //End of destination string found
	}

	while (*dest++ = *src++)
	{
		;           //Copy the source string to the destination string
	}

	return ret;
}

int main()
{
	char arr1[6] = "ab";
	char arr2[] = "cd";
	printf("String before append:%s",arr1);

	my_strcat(arr1, arr2);

	printf("\n Appended string:%s", arr1);

	return 0;
}

The following figure shows its implementation details:

Library function str

strstr is a library function that determines whether a string is a substring of another string. The following is the information given on the C and C + + official websites:

Use of STR function

Let's call this function through a small case.

The following are the main features of this function:

  • The function of strstr function is to judge whether the source string is a substring of the target string;
  • If the source string is a substring of the target string, the starting address of the substring for the first time in the target string is returned;
  • NULL pointer is returned if the source string is not a substring of the destination string.

Simulation Implementation of STR function

Through the previous use and analysis, we can write our own code to simulate and implement the basic functions of STR function.

#include <stdio.h>

char* my_strstr(char* dest, char* src)
{
	char* pc = dest;  //The pc is used to record the address of the substring for the first time
	char* s1 = dest;
	char* s2 = src;
	
	if (*src == '\0')
	{
		return dest;
	}

	while (*pc)
	{
		s1 = pc;
		s2 = src;

		while ((*s1 != '\0') && (*s2 != '\0') && (*s1 == *s2))
		{
			s1++;
			s2++;
		}

		if (*s2 == '\0')
		{
			return pc;  //Is a substring that returns the address of the first occurrence
		}

		pc++;
	}

	return NULL;   //Not a substring, returns a null pointer
}

int main()
{
	char arr1[] = "abc";
	char arr2[] = "ac";

	char* r = my_strstr(arr1, arr2);
	if (r == null)
	{
		printf("arr2 no arr1 Substring of\n");
	}
	else
	{
		printf("arr2 yes arr1 Substring of\n");
	}


	return 0;
}

The following figure shows its implementation details:

If the source string is a substring of the target string, the pc does not need to traverse all positions of the target string. On the contrary, the pc needs to move until the end of the target string.

Functions related to memory copy

Library function memcpy

memcpy library function has the function of memory copy. The following is the information given on the C and C + + official websites:

Use of memcpy function

Let's call this function through a small case.

The following are the main features of this function:

  • memcpy function can copy data from a specific location to another location;
  • The data type stored at the address received by the parameter is not limited;
  • Copy the contents of one byte at a time until the set size is copied;
  • Data with overlapping space cannot be copied.

Simulation of memcpy function

Through the previous use and analysis, we can write our own code to simulate and realize the basic functions of memcpy function.

#include <stdio.h>

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

	while (count--)
	{
		*(char*)dest = *(char*)src;  //Copy 1 byte at a time
		dest = (char*)dest + 1;
		src = (char*)src + 1;
	}

	return ret;

}
int main()
{
	int arr1[] = { 1, 2, 3, 4, 5};
	int arr2[] = { 2, 3, 4, 5, 6};

	printf("Array before copying: ");
	int i = 0;
	for (i = 0; i < 5; i++)
	{
		printf("%d ", arr2[i]);
	}

	my_memcpy(arr2, arr1, 3);

	printf("\n Copied array: ");

	for (i = 0; i < 5; i++)
	{
		printf("%d ", arr2[i]);
	}

	return 0;
}

The following figure shows its implementation details:

It can be seen from the internal implementation of this function that one byte is copied at a time. No matter what type of data is received, it only needs to control the number of bytes to be copied to realize multi-type data copying, so it has strong universality.

Library function memmove

The memmove function can copy data in overlapping memory space. The following is the information given on the C and C + + official websites:

Use of memmove function

Let's call this function through a small case.

The features of this function are as follows:

  • The memmove function can copy data from a specific location to another location;
  • The data type stored at the address received by the parameter is not limited;
  • Copy the contents of one byte at a time until the set size is copied;
  • Can copy data with overlapping space.

Simulation of memmove function

Through the previous use and analysis, we can write our own code to simulate and implement the basic functions of memmove function.

#include <stdio.h>

void* my_memmove(void* dest, void* src, size_t count)
{
	void* ret = dest;
	
	if (dest < src)     //The destination space location is to the left of the source space location, copying from front to back
	{
		while (count--)  //count controls the number of cycles
		{
			*(char*)dest = *(char*)src;
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}
	else      //The destination space location is on the right side of the source space location, copying from back to front
	{
		while (count--)
		{
			*((char*)dest + count) = *((char*)src + count);
		}
	}

	return ret;
}

int main()
{
	int arr[] = { 0, 1, 2};

	printf("Array before copy:");
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		printf("%d ", arr[i]);
	}
	
	my_memmove(arr + 1, arr, 4);

	printf("\n Array after copying:");
	
	for (i = 0; i < 3; i++)
	{
		printf("%d ", arr[i]);
	}

	return 0;
}

The following figure shows its implementation details:

The copy order depends on the relative position between the source space address and the target space address, because improper selection of the copy order will lead to subsequent data that has not been copied in time to be overwritten, resulting in subsequent copy errors.

epilogue

All kinds of library functions provided by C language standard are different from and related to each other. Reasonable selection of library functions can achieve the desired purpose. For string and character array related operations, select the function of string related family; For the copying of data related to other types of arrays, try to select memory related functions to achieve the desired purpose.

This is all the content of today's article. I hope all my friends can gain something. Bye~~

Tags: C Algorithm visualstudio

Posted on Mon, 20 Sep 2021 07:18:25 -0400 by lttldude9