Memory operation functions (memcpy, memmove, memset, memcmp)—-C language

Article directory

  • Summary
  • 1.memcpy
    • 1.1 Function introduction
    • 1.2 Simulation implementation
  • 2.memmove
    • 2.1 Function introduction
    • 2.2 Simulation implementation
  • 3. memset
    • 3.1 Function introduction
  • 4.memcmp
    • 4.1 Function introduction

Abstract

This article introduces commonly used memory operation functions in C language, including memcpy, memmove, memset and memcpy. These functions handle the copying, moving, and initialization of memory data. In the article, these functions are explained in detail, demonstrated with examples, and simulated.

1. memcpy

1.1 Function introduction

Function prototype:

void* memcpy (void* destination, const void* source, size_t num);
  • destination: destination address, indicating the location where the copied data is stored.
  • source: Source address, indicating the starting position of the data to be copied.
  • num: Number of bytes to copy.

memcpy is a library function that copies the contents of one memory area to another memory area. This function copies the contents of the first num bytes of the space pointed by the source address src to the space pointed by the target address dest.
The following code shows how to copy a string using the memcpy function:

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

int main() {<!-- -->
    const char* src = "Hello, world!";
    char dest[20];

    // Use memcpy to copy the string
    memcpy(dest, src, src);

    //Print the copied string
    printf("Copied string: %s\\
", dest);

    return 0;
}
  • Notice:
  • memcpy does not check whether the source and destination addresses overlap, so you need to make sure no overlap occurs when using it.
  • The C language standard stipulates: memcpy to complete non-overlapping memory copy. If you want to complete the copy of memory overlap, you can use the memmove function.

1.2 Simulation implementation

Implementation ideas:

  • Create a loop that copies byte by byte from the source address to the destination address.
  • In the loop, the content of one byte is read from the space pointed to by the source address src, and then written to the space pointed by the destination address dest.
  • Repeat the above steps until num bytes have been copied.
  • After the copy is completed, return the starting address _dest of the target space.
#include <assert.h>

void* my_memcpy(void* dest, const void* src, size_t num)
{<!-- -->
assert(src & amp; & amp; dest);//Check whether the parameters are valid
void* _dest = dest;//Save the starting address of the target space
//Copy byte by byte, copy num bytes
while (num--)
{<!-- -->
//Read the content of a byte from the space pointed to by src, and then write it to the space pointed by dest in the target address space
*(char*)dest = *(char*)src;
\t\t
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return _dest;
}

int main()
{<!-- -->
const char *src = "Hello, world!";
char dest[20];
\t
// Use my_memcpy to copy the string
my_memcpy(dest, src, strlen(src) + 1);
\t
//Print the copied string
printf("Copied string: %s\\
", dest);
return 0;
}

2.memmove

2.1 Function introduction

Function prototype:

void* memmove (void* destination, const void* source, size_t num);
  • destination: destination address, indicating the location where the copied data is stored.
  • source: Source address, indicating the starting position of the data to be copied.
  • num: Number of bytes to copy.

memmove is a library function used to copy the contents of one memory area to another memory area.This function copies the contents of the first num bytes of the space pointed to by the source address source to the space pointed by the destination address. . Unlike the memcpy function, this function can handle overlapping memory areas.
The following code shows how to use the memmove function to handle overlapping memory areas:

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

int main()
{<!-- -->
    char str[] = "abcdef";

    // Use memmove to move "abcd" in "abcdef" to the location of "cdef"
    memmove(str + 2, str, 4);

    //Print the moved string
    printf("Moved string: %s\\
", str);

    return 0;
}

2.2 Simulation implementation

Implementation ideas:
There may be two situations regarding memory overlap:

  • Case 1: src < dest

    At this time, you should start from the last byte of the space pointed to by src and copy it byte by byte in reverse order.
  • Case 2: src > dest

    In this case, there will be no overwriting problem when copying from the first byte of the space pointed to by src, so the copy sequence is as follows:
#include <stdio.h>
#include <assert.h>

void* my_memmove(void* dest, const void* src, size_t num)
{<!-- -->
assert(dest & amp; & src);//Check whether the parameters are legal
void* _dest = dest;//Save the starting address of the target space
//Check copy direction
if (src > dest)
{<!-- -->
//Copy in order
for (int i = 0; i < num; + + i)
{<!-- -->
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else if(src < dest)
{<!-- -->
//Copy in reverse order
while (num--)
{<!-- -->
*((char*)dest + num)= *((char*)src + num);
}
}
return _dest;//Return the starting address of the target space
}
int main()
{<!-- -->
char str[] = "abcdef";

// Use my_memmove to move "abcd" in "abcdef" to the location of "cdef"
my_memmove(str, str + 2, 4);

//Print the moved string
printf("Moved string: %s\\
", str);

return 0;
}

3. memset

3.1 Function introduction

Function prototype:

void* memset (void* ptr, int value, size_t num);
  • ptr: The starting address of the memory area to be set.
  • value: The value to set (usually an integer, interpreted as an unsigned character).
  • num: The number of bytes to set.

memset is a library function used to set the contents of a memory area to a specified value. It is often used to initialize memory. This function sets num consecutive bytes starting from the starting address ptr to the specified value value.
The following code shows how to use the memset function to initialize all elements of an integer array to zero:

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

int main()
{<!-- -->
    int arr[5];

    // Use memset to initialize all elements of the integer array to zero
    memset(arr, 0, sizeof(arr));

    //Print the initialized array
    for (int i = 0; i < 5; i + + )
    {<!-- -->
        printf("%d ", arr[i]);
    }
    printf("\\
");
    return 0;
}

4. memcmp

4.1 Function introduction

Function prototype:

int memcmp ( const void * ptr1, const void * ptr2, size_t num );
  • ptr1: The starting address of memory area 1 to be compared.
  • ptr2: The starting address of memory area 2 to be compared.
  • num: Number of bytes to compare.

memcmp is a library function used to compare the contents of two memory areas. This function compares the first num bytes of the memory area pointed to by ptr1 and ptr2, and returns an integer value representing the comparison result. The meaning of the return value is as follows:

  • If ptr1 and ptr2 are equal, 0 is returned.
  • If ptr1 is less than ptr2, a negative number is returned.
  • If ptr1 is greater than ptr2, a positive number is returned.

The following code demonstrates how to use the memcmp function to compare two strings for equality:

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

int main()
{<!-- -->
    const char *str1 = "abcdef";
    const char *str2 = "abcd";

    // Use memcmp to compare whether two strings are equal
    int res = memcmp(str1, str2, 4);
    
    if (res == 0)
    {<!-- -->
        printf("String equal\\
");
    }
    else {<!-- -->
        printf("Strings are not equal\\
");
    }

    return 0;
}

At this point, this article is over. If the content of this article is helpful to you, please like, follow, and collect it three times in a row to support it.
Creation is not easy, and free prostitution is not good. Your support and recognition are the biggest motivation for my creation. See you in the next article!
If there are any errors in this blog, please criticize and point out, I would be very grateful!