Compare the usage of memccpy of function and memcpy of function in C language

  • 2020-04-02 03:16:48
  • OfStack

C memccpy() function: copies the contents of memory
The header file:


#include <string.h>

Definition function:


void * memccpy(void *dest, const void * src, int c, size_t n);

Memccpy () is used to copy the memory contents of SRC to the address denoted by dest for the first n bytes. Unlike memcpy(), memccpy() checks whether the parameter c is present at replication time, and if so returns the next byte address of the dest value of c.

Return value: returns the next byte pointer to the value c in dest. A return value of 0 indicates that there are no bytes with a value of c in the first n bytes of memory referred to by SRC.

sample


#include <string.h>
main(){
  char a[] = "string[a]";
  char b[] = "string(b)";
  memccpy(a, b, 'B', sizeof(b));
  printf("memccpy():%sn", a);
}

Execution results:


memccpy():string(b)

C memcpy() function: copy memory contents (ignore \0)
The header file:


#include <string.h>

Memcpy () is used to copy memory, and its prototype is:


  void * memcpy ( void * dest, const void * src, size_t num );

Memcpy () copies the first num bytes of the memory content referred to by SRC to the memory address referred to by dest.

Memcpy () doesn't care about the data type being copied, it just copies verbatim sections, which gives the function a lot of flexibility to replicate for any data type.

Note:
The dest pointer allocates enough space, that is, space greater than or equal to num bytes. If space is not allocated, a break error occurs.
Memory space denoted by dest and SRC cannot overlap (if overlap occurs, it is safer to use memmove()).

Unlike strcpy(), memcpy() copies num bytes in their entirety and does not end up with "\0".

Returns a pointer to dest. Note that the returned pointer type is void and is typically cast when used.


Code example:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N (10)
int main()
{
  char* p1 = "abcde";
  char* p2 = (char*)malloc(sizeof(char) * N);
  char* p3 = (char*)memcpy(p2, p1, N);
  printf("p2 = %snp3 = %sn", p2, p3);
  free(p2);
  p2 = NULL;
  p3 = NULL;
  system("pause");
  return 0;
}

Operation results:


p2 = abcde
p3 = abcde

Code description:
1) the code first defines three Pointers, p1, p2 and p3, but with a slight difference, p1 points to a string literal, and p2 is allocated 10 bytes of memory space.

2) pointer p3 directly points to the memory pointed by pointer p2 through the function memcpy, that is to say, Pointers p2 and p3 point to the same memory. Then print the memory value pointed to by p2 and p3, and the result is the same.

3) finally, release p2 according to good habits, and set p3 to NULL to prevent p3 from accessing the memory pointed to by p3 again, resulting in the occurrence of wild pointer.


Related articles: