The format for the memcpy function in the C programming language is as shown below:
void *memcpy(void *arr1, const void *arr2, size_t n);
The memcpy function is responsible for duplicating n specified characters from the source array or position, with arr1 serving as the source and arr2 as the destination. Both arr1 and arr2 act as pointers pointing to the source and destination positions, respectively.
Parameter or Arguments passed in memcpy
- arr1: it is the first parameter in the function that specifies the location of the source memory block. It represents the array that will be copied to the destination.
- arr2: The second parameter in the function specifies the location of the destination memory block. It represents the array where the memory block will be copied.
- n: It specifies the number of characters copied from source to destination.
Return
It returns a pointer that is the arr1.
Header file
In order to utilize the memcpy function within your code, it is essential to include the string.h header file where the function is defined.
#include<string.h>
Let's explore the process of incorporating the memcpy function within a C program.
//Implementation of memcpy() in C Programming
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[])
{
//initializing a variable that will hold the result./* Create a place to store our results */
int res;
//declare the arrays for which you want to copy the data and
//in which you want to copy it
char orgnl[50];
char copy[50];
//Entering a string the orgnl array
strcpy(orgnl, "This is the program for implementing the memcpy() in C Program");
//use the memcpy() function to copy the characters from the source to destination.
res = memcpy(copy, orgnl, 27);
// we have specified n as 27 this means it will copy the first 27 character of
//orgnl array to copy array
//set the value for last index in the copy as 0
copy[27] = 0;
//display the copied content
printf("%s\n", copy);
return 0;
}
Note: It is necessary to set the last index as null in the copied array as the function only copies the data and does not initialize the memory itself. The string expects a null value to terminate the string.
Important Facts to be Accounted before implementing memcpy in C Programming:
- The memcpy function is declared in the string.h header file. So the programmer needs to ensure to include the file in the code.
- The size of the buffer in which the content is to be copied must be greater than the number of bytes to be copied into the buffer.
- It does not work when the objects overlap. The behavior is undefined if we try to perform the function on the objects that overlap.
- It is necessary to add a null character when using the strings as it does not check for the terminating null characters in the strings.
- The function behavior will not be defined if the function will access the buffer beyond its size of it. It is better to check the buffer size using the sizeof function.
- It does not ensure that the destination memory block is valid in the memory of the system or not.
#include <stdio.h>
#include <string.h>
int main ()
{
//The first step is to initialize the source and destination array.
char* new;
char orgnl[30] = "Movetheobject";
//Print the contents before performing memcpy() function.
printf("Before implementing memcpy() destination and source memory block respt is\n new = %s\n orgnl = %s\n", new, orgnl);
memcpy(new, orgnl, sizeof(orgnl));
//Display the content in both new and orgnl array after implementing memcpy.
printf("After memcpy >> new = %s\n orgnl = %s\n", new, orgnl);
return 0;
}
Output:
[Program Output]
The code's functionality becomes unpredictable when the new pointer is not pointing to a valid location, leading to improper program execution. Certain compilers may even generate an error in such scenarios. The target pointer specified in the aforementioned situation is considered invalid. Additionally, the memcpy function lacks the capability to validate the source buffer.
#include <stdio.h>
#include <string.h>
int main ()
{
//The first step is to initialize the source and destination array.
char new[10]= {1};
char *orgnl;
//Print the contents before performing memcpy() function.
printf("Before implementing memcpy() destination and source memory block respt is\n new = %s\n orgnl = %s\n", new, orgnl);
memcpy(new, orgnl, sizeof(orgnl));
//Display the content in both new and orgnl array after implementing memcpy.
printf("After memcpy >> new = %s\n orgnl = %s\n", new, orgnl);
return 0;
}
Output:
[Program Output]
The resulting output, in this scenario, resembles the previous case where the destination wasn't specified. The distinction lies in the absence of compilation errors. Instead, it exhibits undefined behavior since the source pointer doesn't point to any defined location.
- The functionality of the memcpy functions operates at the byte level of the information. Hence, the value of n needs to be specified in bytes to achieve the intended outcomes.
- Within the memcpy function syntax, both the source and destination memory blocks are defined as void *, enabling them to reference data of any type.
Let's explore several instances demonstrating the utilization of the memcpy function with various data types.
Implementing the memcpy function with char type data
#include <stdio.h>
#include <string.h>
int main()
{
//initialize the source array,
//the data will be copied from source to destination/
char sourcearr[30] = "This content is to be copied.";
//this is the destination array
//data will be copied at this location.
char destarr[30] = {0};
//copy the data stored in the sourcearr buffer into destarr buffer
memcpy(destarr,sourcearr,sizeof(sourcearr));
//print the data copied into destarr
printf("destination array content is now changed to\n = %s\n", destarr);
return 0;
}
Output:
[Program Output]
Here we have declared two arrays with a capacity of 30 elements each. The sourcearr holds the information that will be duplicated into the destarr. The data was transferred to destarr using the memcpy function.
Implementing memcpy(0 function with integer type data
#include <stdio.h>
#include <string.h>
int main()
{
//initialize the source array,
//the data will be copied from source to destination/
int sourcearr[100] = {1,2,3,4,5};
//this is the destination array
//data will be copied at this location.
int destarr[100] = {0};
//copy the data stored in the sourcearr buffer into destarr buffer
memcpy(destarr,sourcearr,sizeof(sourcearr));
//print the data copied into destarr
printf("destination array content is now changed to\n");
for(int i=0;i<5;i++){
printf("%d", destarr[i]);
}return 0;}
Output:
[Program Output]
In this code, we have stored the integers in the array. Both the arrays can store int datatype. We have used the indexes to print the elements of the destarr after copying the elements of the sourcearr into destarr.
Implementing the memcpy function with struct datatype
#include <stdio.h>
#include <string.h>
struct
{
char name[40];
int age;
} prsn1, prsn2;
int main()
{
//
char firstname[]="Ashwin";
//Using the memcpy() function to copy the data from
//firstname to the struct
//add it is as prsn1 name
memcpy ( prsn1.name, firstname, strlen(firstname)+1 );
//initialize the age of the prsn1
prsn1.age=20;
//using the memcpy() function to copy one person to another
//the data will be copied from prsn1 to prsn2
memcpy ( &prsn2, &prsn1, sizeof(prsn1) );
//print the stored data
//display the value stored after copying the data
//from prsn1 to prsn2
printf ("person2: %s, %d \n", prsn2.name, prsn2.age );
return 0;
}
Output:
[Program Output]
In the preceding code snippet, the layout has been specified. The memcpy function was employed on two occasions. Initially, it was utilized to duplicate the string into prsn1, while it was employed a second time to transfer the information from prsn1 to prsn2.
Define your memcpy function in C Programming Language
Implementing the memcpy function in C is relatively straightforward. The logic behind memcpy is simple. To create the memcpy function, you need to cast both the source and destination addresses to char*(1 byte). After the typecasting, proceed to transfer the data from the source array to the destination address byte by byte. Repeat this process until you have copied the specified number of bytes, denoted by 'n'.
Let us code our own memcpy function:
Note: The function below works similarly to the actual memcpy function, but many cases are still not accounted for in this user-defined function. Using your memcpy function, you can decide specific conditions to be included in the function. But if the conditions are not specified, it is preferred to use the memcpy function defined in the library function.
//this is just the function definition for the user defined memcpy() function.
void * MemCpy(void* destinatn, const void* source, unsigned int cn)
{
char *pntDest = (char *)destinatn;
const char *pntSource =( const char*)source;
if((pntDest!= NULL) && (pntSource!= NULL))
{
while(cn) //till cn the loop will be executed
{
//copy the contents from source to dest
//the data should be copied byte by byte
*(pntDest++)= *(pntSource++);
//decrement the value of cn
--cn;
}
}
return destinatn;
}
Let's create a driver code to verify the functionality of the aforementioned code.
Driver Code to test MemCpy Function
In the following code snippet, we will utilize the array arr1 to duplicate the information into the arr2 array using the MemCpy function.
void * MemCpy(void* destinatn, const void* source, unsigned int cn)
{
char *pntDest = (char *)destinatn;
const char *pntSource =( const char*)source;
if((pntDest!= NULL) && (pntSource!= NULL))
{
while(cn) //till cn the loop will be executed
{
//copy the contents from source to dest
//the data should be copied byte by byte
*(pntDest++)= *(pntSource++);
//decrement the value of cn
--cn;
}
}
return destinatn;
}
int main()
{
char src[20] = "How Are you ?"; //Source String
char dst[20] = {0}; //dst buffer
//copy source buffer int dst
MemCpy(dst,src,sizeof(src));
printf("dst = %s\n", dst);
return 0;
}
Output: