C language – simulation implementation of some library functions

Table of Contents

1. Simulate the implementation of strcmp

method one

Method Two

2. Simulate the implementation of strcat

method one

Method Two

3. Simulate the implementation of strstr

method one

Method Two

4. Simulate the implementation of memcpy

method one

Method Two

5. Simulate implementation of memmove

method one

Method Two

6. Simulate and implement strlen

1. Counter mode

2. Cannot create temporary variable counter

3. Pointer-pointer approach

7. Simulate the implementation of strcpy


1. Simulate and implement strcmp

Method 1

int my_strcmp(const char* str1, const char* str2)
{
    while (*str1 & amp; & amp; (*str1 == *str2))
 {
        str1 + + ;
        str2++;
 }
    return *(const unsigned char*)str1 - *(const unsigned char*)str2;
}

The above is a simple code that simulates the strcmp function. It compares the corresponding positions of two strings character by character until a certain character in the two strings is different. Two strings are equal if they reach the end of the string and are still equal. The result of the comparison returns an integer:

  • If str1
  • If str1>str2, return a positive number;
  • If str1=str2, return 0.

Note: Unsigned character pointers are used here because the result obtained by subtracting signed character pointers will be unstable due to the influence of the sign bit.

Method 2

int my_strcmp (const char * src, const char * dst)
{
  int ret = 0;
 assert(src != NULL);
  assert(dest != NULL);
  while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) & amp; & amp; *dst)
     + + src, + + dst;
?
  if(ret<0)
    ret = -1;
  else if(ret>0)
    ret = 1;
?
  return ret;
}

2. Simulate and implement strcat

Method 1

#include <stdio.h>
#include <string.h>

void mystrcat(char* dest, const char* src) {
    while (*dest) { // find the end of dest
        dest + + ;
    }
    while (*src) { // Copy the characters in src to the end of dest in sequence
        *dest + + = *src + + ;
    }
    *dest = '\0'; // Add '\0' at the end of dest to form a string
}

int main() {
    char s1[100] = "hello";
    char s2[] = "world";
    mystrcat(s1, s2);
    printf("%s\
", s1);
    return 0;
}

In the above code, the parameters of the mystrcat function include a char type pointer dest and a const char type pointer src, which represent the destination string and the source string respectively. .

In the function, use a while loop to find the end of the dest string, and then use a while loop to copy the characters in src to the end of dest until it encounters ‘\0’ (string terminator). Finally, add ‘\0’ to the end of dest to form a complete string.

In the main function, two character arrays s1 and s2 are defined, and the contents of s2 are concatenated at the end of s1. Finally, the concatenated string is output.

Method 2

char* my_strcat(char* dest, const char* src)
{
 char* ret = dest;
 assert(dest != NULL);
 assert(src != NULL);
 while(*dest)
 {
  dest + + ;
 }
 while((*dest + + = *src + + ))
 {
  ;
 }
 return ret;
}

3. Simulation and implementation of strstr

Method 1

Used to find whether a string contains another substring:

char *my_strstr(const char *haystack, const char *needle)
 {
    int i, j;
    int n = strlen(haystack); //The length of the string haystack
    int m = strlen(needle); //The length of the string needle
    
    if (m == 0) {
        return (char *) haystack;
    }
    
    for (i = 0; i <= n - m; i + + ) {
        for (j = 0; j < m & amp; & amp; haystack[i + j] == needle[j]; j + + );
        if (j == m) {
            return (char *) haystack + i;
        }
    }
    
    return NULL;
}

This function accepts two parameters, which are the search string haystack and the substring needle to be found.

The function returns a pointer to the first occurrence of the substring in the searched string, or NULL if not found.

The function first obtains the length of the searched string and substring.If the substring length is 0, it directly returns the pointer of the searched string.

The function uses two loops to match the searched string and substring. If the match is successful, it returns the pointer of the first occurrence of the substring in the searched string. If the substringis not found in the loop, NULL is returned.

Method 2

char * strstr (const char* str1, const char* str2)
{
        char* cp = (char*) str1;
        char* s1, *s2;

        if (!*str2)
            return((char*)str1);

        while (*cp)
        {
                s1 = cp;
                s2 = (char*) str2;

                while ( *s1 & amp; & amp; *s2 & amp; & amp; !(*s1-*s2) )
                        s1 + + , s2 + + ;

                if (!*s2)
                        return(cp);

                cp + + ;
        }

        return(NULL);
}

4. Simulate and implement memcpy

Method 1

In C language, the memcpy function can be used to copy data from one memory area to another memory area.

Here is a memcpy function implemented using pointers:

void *my_memcpy(void *dest, const void *src, size_t n)
 {
    char *pdest = (char *)dest;
    const char *psrc = (const char *)src;
    
    for (size_t i = 0; i < n; i + + )
    {
        *(pdest + i) = *(psrc + i);
    }
    
    return dest;
 }

This function accepts three parameters: dest address (dest), source address (src), and the number of bytes to copy (n). Inside the function, we first convert both the target address and the source address to char pointer type, and then copy the data in the memory one by one through the for loop until n bytes have been copied. Finally, the function returns the target address pointer.

Note that no bounds checking is done in this implementation. If n is greater than the size of the memory area pointed to by the target address or source address, then an error will occur in this function. Therefore, in actual use, boundary checking should be performed to ensure that the copied data does not cross the boundary.

Method 2

void * memcpy ( void * dst, const void * src, size_t count)
{
  void * ret = dst;
    assert(dst);
  assert(src);
  /*
   * copy from lower addresses to higher addresses
   */
  while (count--) {
    *(char *)dst = *(char *)src;
    dst = (char *)dst + 1;
    src = (char *)src + 1;
  }

  return(ret);
}

5. Simulate and implement memmove

Method 1

The memmove() function is used to move a memory block of a specified length from one location to another. Unlike the memcpy() function, the memmove() function can handle the source address and In case of overlapping destination addresses.

The following is the code that uses C language to simulate the memmove() function:

void* memmove(void* dest, const void* src, size_t n)
{
    char* pdest = (char*)dest;
    const char* psrc = (const char*)src;
    char* tmp = NULL;

    // Determine whether it is necessary to borrow the temporary buffer
    if (pdest > psrc & amp; & amp; pdest - psrc < n)
    {
        tmp = (char*)malloc(n);
        if (tmp == NULL)
        {
            return NULL;
        }
        memcpy(tmp, psrc, n);
        psrc = tmp;
    }

    //Move from front to back
    if (pdest <= psrc)
    {
        while (n--)
        {
            *pdest + + = *psrc + + ;
        }
    }
    //Move from back to front
    else
    {
        pdest + = n;
        psrc + = n;
        while (n--)
        {
            *--pdest = *--psrc;
        }
    }

    // Release temporary buffer
    if (tmp != NULL)
    {
        free(tmp);
    }

    return dest;
}

This is a code that implements the memory copy function memmove. Its function is to copy n bytes in the source memory area src to the target memory area dest.

The implementation of this function is to realize memory movement through two pointers pdest and psrc. If the target area is in front of the source area, move from front to back, otherwise move from back to front. If the target area is in front of the source area and the two areas overlap, you need to use a temporary buffer.

The specific implementation steps are as follows:

  1. Convert the void type dest and src pointers to char type pointers to facilitate pointer displacement operations.

  2. Determine whether a temporary buffer is needed. If the target area is in front of the source area and the two areas overlap, you need to use a temporary buffer. At this time, first apply for a temporary buffer tmp of size n, and copy the data in src to tmp.

  3. Depending on the relationship between the target area and the source area, you can choose to move the memory data from front to back or from back to front. The specific implementation method is to use a while loop to traverse the memory area and copy the data from the source memory area to the target memory area in sequence, or vice versa.

  4. If a temporary buffer is used, it needs to be released after the operation is completed.

  5. Finally, the pointer to the target memory area dest is returned.

#include 
#include 

void* memmove(void* dest, const void* src, size_t n)
{
    char* pdest = (char*)dest;
    const char* psrc = (const char*)src;
    char* tmp = NULL;

    // Determine whether it is necessary to borrow the temporary buffer
    if (pdest > psrc & amp; & amp; pdest - psrc < n)
    {
        tmp = (char*)malloc(n);
        if (tmp == NULL)
        {
            return NULL;
        }
        memcpy(tmp, psrc, n);
        psrc = tmp;
    }

    //Move from front to back
    if (pdest <= psrc)
    {
        while (n--)
        {
            *pdest + + = *psrc + + ;
        }
    }
    //Move from back to front
    else
    {
        pdest + = n;
        psrc + = n;
        while (n--)
        {
            *--pdest = *--psrc;
        }
    }

    // Release temporary buffer
    if (tmp != NULL)
    {
        free(tmp);
    }

    return dest;
}

int main()
{
    char str[] = "Hello World!";
    memmove(str + 6, str, 5);
    printf("%s\
", str); // Output "Hello Hello!"

    return 0;
}

In the above code,

First, use pointers to convert the target address and source address to char* type, and then choose to move from front to back or from back to front based on the positional relationship between the target address and the source address. If the target address is after the source address, then move from back to front; if the target address is before the source address, then move from front to back. When moving from back to front, you need to move the pointer to the end first, and then copy from back to front. If the destination address and source address overlap, a temporary buffer needs to be borrowed for intermediate storage. Finally, Pay attention to releasing the memory of the temporary buffer.

Method 2

void * memmove ( void * dst, const void * src, size_t count)
{
  void * ret = dst;
?
  if (dst <= src || (char *)dst >= ((char *)src + count)) {
    /*
    * Non-Overlapping Buffers
    * copy from lower addresses to higher addresses
    */
    while (count--) {
        *(char *)dst = *(char *)src;
        dst = (char *)dst + 1;
        src = (char *)src + 1;
     }
   }
  else {
    /*
    * Overlapping Buffers
    * copy from higher addresses to lower addresses
    */
    dst = (char *)dst + count - 1;
    src = (char *)src + count - 1;
?
    while (count--) {
        *(char *)dst = *(char *)src;
        dst = (char *)dst - 1;
        src = (char *)src - 1;
     }
   }
  return(ret);
}

6. Simulation and implementation of strlen

The trlen function is used to calculate the length of a string (excluding the ‘\0’ at the end of the string),

The following is the code to simulate strlen in C language:

#include <stdio.h>

int my_strlen(const char *s) {
    int len = 0;
    while (*s != '\0') { // The loop condition is that the current character is not the '\0' at the end of the string
        len + + ; // length plus one
        s + + ; // Move pointer back
    }
    return len;
}

int main() {
    char str[] = "Hello, world!";
    printf("length of str: %d\
", my_strlen(str)); // The output length is 13
    return 0;
}

The parameters of the my_strlen function here are the same as strlen, which are both pointers to char. Inside the function, a while loop is used to traverse the entire string, adding one to the length each time a character is traversed, and finally returning the calculated length.

1. Counter mode

int my_strlen(const char * str)
{
 int count = 0;
 while(*str)
 {
  count + + ;
  str + + ;
 }
 return count;
}

2. Cannot create temporary variable counter

int my_strlen(const char * str)
{
 if(*str == '\0')
  return 0;
 else
  return 1 + my_strlen(str + 1);
}

3. Pointer-pointer method

int my_strlen(const char *s)
{
   char *p = s;
   while(*p != \0’ )
       p + + ;
   return p-s;
}

7. Simulate and implement strcpy

The strcpy function is a string copy function in C language.

Used to copy the contents of one string to another string.

The following is the code to simulate strcpy in C language:

char* my_strcpy(char* dest, const char* src)
{
 char* ret = dest;
 assert(dest != NULL);
 assert(src != NULL);
 
 while((*dest + + = *src + + ))
 {
  ;
 }
 return ret;
}
#include <stdio.h>

char* my_strcpy(char* dest, const char* src) {
    char* p = dest;
    while (*src) {
        *dest + + = *src + + ;
    }
    *dest = '\0';
    return p;
}

int main() {
    char s1[20] = "Hello";
    char s2[20] = "World";
    printf("Before copy: %s %s\
", s1, s2);
    my_strcpy(s1, s2);
    printf("After copy: %s %s\
", s1, s2);
    return 0;
}

In the above code, themy_strcpy function accepts two parameters, one is the destination string (i.e., the string that needs to be copied), and the other is the string to be copied (i.e., the source string). In the function, use the p pointer to save the first address of the destination string, and then copy each character in the source string to the destination string one by one through a loop, >Until the source string terminator ‘\0’ is encountered. Finally, add ‘\0’ as the terminator at the end of the destination string, and return the first address of the destination string. In the main function, first output the initial values of the two strings, thencall the my_strcpy function to copy the contents of the s2 string to the s1 string, and output the final values of the two strings.

The output is as follows:

Before copy: Hello World
After copy: World World

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. C skill treeFunction and program structureDeclaration and definition of function 192938 people are learning the system