Table of contents
1.
Introduction
2.
Understanding memcpy() in C
3.
Syntax of memcpy() in C
4.
Return Type of memcpy() in C
5.
Parameters of memcpy() in C
5.1.
Time Complexity
5.2.
Space Complexity
6.
Exceptions of memcpy() in C
7.
Copying Values of a struct to a char buffer
7.1.
Implementation
7.2.
C
7.2.1.
Explanation
8.
Copying Data from One Dynamic Array to Another
8.1.
Implementation
8.2.
C
8.2.1.
Output
8.2.2.
Explanation
9.
Copying a String
9.1.
Implementation
9.2.
C
9.2.1.
Output
9.2.2.
Explanation
10.
Copying a Block of Memory to a Dynamic Memory Allocation
10.1.
Implementation
10.2.
C
10.2.1.
Output
10.2.2.
Explanation
11.
Passing Non-Pointer Variables
11.1.
Implementation
11.2.
C
11.2.1.
Output
11.2.2.
Explanation
12.
Using Overlapping Memory Locations
12.1.
Implementation
12.2.
C
12.2.1.
Output
12.2.2.
Explanation
13.
Common Errors When Using memcpy C
13.1.
Passing NULL Pointers as an Argument 
13.1.1.
Implementation
13.2.
C
13.2.1.
Output
13.2.2.
Explanation
13.3.
Providing an Incorrect Size Argument
13.3.1.
Implementation
13.4.
C
13.4.1.
Output
13.4.2.
Explanation
14.
Applications of memcpy() in C
15.
Advantages of Memcpy() in C
16.
Disadvantages of Memcpy() in C
17.
Frequently Asked Questions
17.1.
Can the function memcpy() be used to copy memory?
17.2.
Is memcpy faster than a loop?
17.3.
What is the difference between strcpy and memcpy?
17.4.
Is memcpy faster than loop?
17.5.
What are the three parameters of memcpy?
18.
Conclusion
Last Updated: Sep 16, 2024
Easy

memcpy() in C

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

memcpy() in C is a standard library function which is used to copy a specified number of bytes from one memory location to another. It belongs to the <string.h> library. Unlike strcpy(), which is for strings, memcpy() works with any data type and doesn't stop at a null character. It’s widely used for copying arrays, structures, and other memory blocks in C programs, ensuring efficient memory handling.

memcpy() in C

In this article, we will learn about the memcpy() in C. We will discuss how it works and can make your code error-prone. So let's discover the memcpy() function in depth.

Understanding memcpy() in C

memcpy() is a built-in function in C. The memcpy function in C is used to copy a specified number of bytes from one memory location to another. memcpy C is mainly used for copying data from one array to another. Ensure that the memory regions you are copying do not overlap. The number of bytes to copy must be specified beforehand. This function returns the destination memory pointer. The memory areas you are copying must be of the same data type. memcpy() is an efficient way to quickly copy large amounts of data. Using memcpy() can help improve C code performance.

Syntax of memcpy() in C

void* memcpy(void* a, const void*  b, size_t n);


a - destination pointer

b - source pointer

n - number of bytes to copy

Return Type of memcpy() in C

void* is the return type of memcpy() C. memcpy() returns a pointer to the destination memory block.

Parameters of memcpy() in C

void* aThis destination memory pointer is a pointer to the memory block you wish to copy data to. 

const void* bThis source memory pointer is a pointer to the memory block you want to copy data from.

size_t n - n is the number of bytes you want to copy.

Time Complexity

O(N): As in the above code, the source memory gets copied into the destination memory, and the source size is N, so the time complexity is O(N).

Space Complexity

O(1): Memory usage remains constant regardless of the data size you are copying. The temporary variables are used to store intermediate values. memcpy() function does not allocate additional memory for its operation.

Now we will discuss some examples of using the memcpy() C function. 

Exceptions of memcpy() in C

The exceptions of memcpy() in C are as follows:

  • Buffer Overflow
    This means that if the destination buffer is too small to hold the source buffer, it will overwrite the memory beyond the end of the destination buffer. This can lead to unwanted and undefined behaviour. To prevent this, there is an updated version of memcpy() in C11 called memcpy_s. The syntax is as follows:
errno_t memcpy_s( void *restrict destination, rsize_t destination_size, const void *restrict source, rsize_t size );


It has an extra parameter as destination size, the maximum size of the destination buffer. This way, if the source buffer size is larger than the destination buffer, the program will stop the execution.
 

  • Alignment issues
    It means that if the source or the destination buffers are not adequately aligned, memcpy() will not work correctly. It can lead to unwanted and undefined behaviors or even crashes.

Copying Values of a struct to a char buffer

The memcpy() function copies the entire struct layout to a buffer. You have to pass a pointer to the struct as the source argument, the buffer as the destination argument, and the size of the struct. If the struct in your code has pointers, handle them separately. 

Implementation

  • C

C

#include <stdio.h>
typedef struct {
   int id;
   char name[20];
   float questions_solved;
} Programmer;
int main() {
   
   // Here, we are creating an instance of the Programmer struct and initializing it with some values
   Programmer p = { 1, "Ninja", 450};
   
   // Here, we are creating a char buffer the same size as the Programmer struct.
   char buffer[sizeof(Programmer)];
   
   // Now we are copying the contents of the p struct to the buffer using memcpy()
   memcpy(buffer, &p, sizeof(Programmer));
   
   // Finally, extract the individual values from the buffer and print the output
   printf("ID: %d\n", *(int*)(buffer));
   printf("Name: %s\n", (char*)(buffer + sizeof(int)));
   printf("Questions Solved: %.2f\n", *(float*)(buffer + sizeof(int) + sizeof(char[20])));
   
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

OUTPUT

Explanation

Firstly this code creates a " Programmer " struct with three fields (id, name, and questions_solved). A char buffer is made with the same size as the Programmer struct. The contents of the struct are then copied to the buffer using memcpy(). Finally, the individual values are extracted from the buffer.

Recommended topic, Tribonacci Series and  Short int in C Programming

Copying Data from One Dynamic Array to Another

It involves creating two dynamic arrays. Then add values in one array. Finally, use memcpy() to copy the contents of one array to the other.

dry run

Implementation

  • C

C

#include <stdio.h>
main() {
   int n = 5;
   int p[] = {80, 75, 90, 95, 85};
   
   // declaring the second array with size n
   int q[n];

   // printing the first array
   printf("Marks in first array : ");
   for (int i = 0; i < n; i++) printf("%d ", p[i]);
   memcpy(q, p, n * sizeof(int)); // copying p array to q array
  
   printf("\nMarks in second array: ");
   for (int i = 0; i < n; i++) printf("%d ", q[i]);
   return 0;
You can also try this code with Online C Compiler
Run Code

 

Output

OUTPUT

Explanation

The values in the first array are initialized. The memcpy C function is used to copy the data of the first array to the second array. Finally, both arrays are printed.

Copying a String

It is easier than manually copying each character. You can use memcpy() to copy characters from the source string to the destination string. 

Implementation

  • C

C

#include <stdio.h>
main() {
// Firstly we are declaring and initializing str1 with some text
   char s[] = "Hey Ninjas! How it's going";
   
// Now declare an empty char array of length 27
   char p[27];
   
// Copying the contents of p to q using memcpy
   memcpy(p, s, 27);
   printf("string 1 is : %s\n", s);
   printf("string 2 is : %s\n", p);
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

OUTPUT

Explanation

Create a character array named s and initialise it with the desired values. Then specify a length and a name for the empty character array p. To copy the text from s to p, use the memcpy function.

Copying a Block of Memory to a Dynamic Memory Allocation

Allocate the memory using malloc(). Firstly, you have to set the destination pointer to the address of the allocated memory block. The destination memory block will have the data you copied. Set the source memory pointer address of the source memory block. The source memory block is where you want to copy the data. Determine the number of bytes you want to copy from the source memory block to the destination memory block.

Implementation

  • C

C

#include <stdio.h>

// Defining a constant macro with a value of 10
#define BLOCK_SIZE 10
main() {

// Here we are declaring and initializing a char array
char phone_number[BLOCK_SIZE] = "7895678000";

// Now declare a pointer to char and allocate memory dynamically
char *dynamic_block = malloc(BLOCK_SIZE);

// Copying using memcpy
memcpy(dynamic_block, phone_number, BLOCK_SIZE);
printf("Dynamic block: %s\n", dynamic_block);

// Finally, deallocate the memory allocated dynamically
free(dynamic_block);
return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

OUTPUT

Explanation

This code copies a phone number string into a dynamically allocated memory block using memcpy C. Finally prints the contents of the block and deallocates the memory.

Passing Non-Pointer Variables

Attempting to pass non-pointer variables to the function can sometimes result in errors.

Implementation

  • C

C

#include <stdio.h>
main() {

// defining the two integer
   int a = 78;
   int b = 90

// Now we will use memcpy to copy the value of a into b
   memcpy(&a, &b, sizeof(int));
  
   printf("The value of a is : %d\n", a);
   printf("The value of b is : %d\n", b);
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

OUTPUT

Explanation

memcpy() function will expect pointers to the source and destination memory locations. Use the address-of operator & to get pointers.

Using Overlapping Memory Locations

The function may produce unpredictable results. memcpy C is designed to work with non-overlapping memory. memmove() is specifically designed to handle overlapping memory locations. Try using memmove().

overlapping memory locations

Implementation

  • C

C

#include <stdio.h>
main() {
   
   // First we define a string with some initial text
   char string_n[] = "Hey, Ninjas!";
  
   /* We copy the first 7 characters of the string to the second 7 characters.
    The first 7 characters are copied to positions 7-13.
   */
   memcpy(string_n + 7, string_n, 7);

   // Printing the modified string
   printf("%s\n", string_n);
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

OUTPUT

Explanation

Here we use the memcpy function to copy a substring of the array to a different location in the same array. The source and destination pointers refer to the same array. You effectively overlap the memory regions you are copying.

Common Errors When Using memcpy C

Here are common errors that can occur when using memcpy C :

Passing NULL Pointers as an Argument 

The function may crash if the source or destination pointer passed to the memcpy() function is NULL. Perform a NULL check before calling the function.

Implementation

  • C

C

#include <stdio.h>
void cpy_str_function(char *destination, const char *source, size_t n) {
  
   // we are checking if either pointer is NULL
   if (source == NULL || destination == NULL) {
      
      // print an error message
       printf("There's an Error: source or destination pointer is NULL\n");
     
// return without copying anything
       return;
   }
 
// copying n bytes from source to destination
   memcpy(destination, source, n);
}
main() {
   char *sou_rce = "Hey, Ninjas!";

// allocating memory for the destination string
   char *desti_nation = malloc(strlen(sou_rce) + 1);

// Here we are checking whether allocation failed
   if (desti_nation == NULL) {
       printf("Error: failed to allocate memory\n");
       return 1;
   }
   cpy_str_function(desti_nation, sou_rce, strlen(sou_rce) + 1);
   printf("%s\n", desti_nation);
   free(desti_nation);
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

output

 

Explanation

Before copying anything, this code checks if the source or destination string is NULL. If either is NULL, it prints an error message and returns without copying. In the main function, we allocate memory for the destination string. We checked if the allocation failed. If allocation fails, we print an error message.

Providing an Incorrect Size Argument

The size argument passed to the memcpy() function should be the number of bytes you want to copy. If you provide too small an argument, the function may not copy all the required data, resulting in missing data. If you provide too large size argument, the memcpy function may copy more data than needed, leading to buffer overflows.

Implementation

  • C

C

#include <stdio.h>
main() {
   char source[] = "We are testing a string.";

//Declare the destination array with size you want
   char destination[10]
/*
Now try passing a size larger than the destination array size. You will see error due to buffer overflow
*/
   memcpy(destination, source, 60);
   printf("%s\n", destination);
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

error

 

Explanation

Firstly we initialize a character array source with a string value. Then we declare a character array destination with a size of 10. Then we try to copy the data of the source array to the destination array using the memcpy function with a size argument of 60. 60 is larger than the destination array size (10), which can lead to a buffer overflow.

Buffer overflow can corrupt memory. It can cause program crashes.

Applications of memcpy() in C

Here are some real-life applications of memcpy C : 

  1. In a multi-threaded application, it helps transfer data between threads. 
     
  2. It is used in graphics programming when copying image or video data.
     
  3. Data serialization and deserialization in network communication protocols use it.
     
  4. It can implement queues, stacks, and list-based data structures. 
     
  5. State-saving and state-loading in games are implemented using it.
     
  6. Additionally, it manages how memory is allocated in dynamic programming.

Advantages of Memcpy() in C

  • It is easy to use and implement for copying data in memory.
     
  • It is valuable for copying large amounts of data faster.
     
  • It gives a safe way to copy data.
     
  • It helps perform data manipulations and transformations.
     
  • It can be used in low-level programming for memory management.

Disadvantages of Memcpy() in C

  • It may not be safe to copy data between overlapping memory regions.
     
  • It needs attention to the copied data's size and type to avoid errors.
     
  • It does not perform error checking or verification on the data being copied.
     
  • It may only be suitable for some data copy operations.
     
  • It has limited use for more advanced data handling.

Frequently Asked Questions

Can the function memcpy() be used to copy memory?

Yes, the memcpy() function in C can be used to copy memory effectively. It is specially designed for this purpose.

Is memcpy faster than a loop?

Yes, the memcpy() function in C is faster than a loop for copying memory due to its optimized implementation.

What is the difference between strcpy and memcpy?

strcpy() copies null-terminated strings, while memcpy() copies a fixed number of bytes regardless of data type or null characters.

Is memcpy faster than loop?

Yes, memcpy() is faster than manual loops as it is optimized for memory copying at the hardware or system level.

What are the three parameters of memcpy?

memcpy() has three parameters: the destination pointer, the source pointer, and the number of bytes to copy.

Conclusion

This article discusses the memcpy C function. It explains the definition, pros, cons, applications and usage of memcpy, along with examples. The article helps to make learning memcpy easier. It also includes code snippets to help understand the function in different cases. To improve your understanding, refer to other C programming articles.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses, refer to the mock test and problems look at the interview experiences and interview bundle for placement preparations.

Live masterclass