Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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.
CODE
7.2.
C
7.2.1.
OUTPUT
7.2.2.
EXPLANATION
8.
Copying Data from One Dynamic Array to Another
8.1.
CODE
8.2.
C
8.2.1.
OUTPUT
8.2.2.
EXPLANATION
9.
Copying a String
9.1.
CODE
9.2.
C
9.2.1.
OUTPUT
9.2.2.
EXPLANATION
10.
Copying a Block of Memory to a Dynamic Memory Allocation
10.1.
CODE
10.2.
C
10.2.1.
OUTPUT
10.2.2.
EXPLANATION
11.
Passing Non-Pointer Variables
11.1.
CODE
11.2.
C
11.2.1.
OUTPUT
11.2.2.
EXPLANATION
12.
Using Overlapping Memory Locations
12.1.
CODE
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.
CODE
13.2.
C
13.2.1.
OUTPUT
13.2.2.
EXPLANATION
13.3.
Providing an Incorrect Size Argument
13.3.1.
CODE
13.4.
C
13.4.1.
OUTPUT
13.4.2.
EXPLANATION
14.
Applications of memcpy() in C
15.
Pros & Cons of Memcpy() in C
15.1.
Pros
15.2.
Cons
16.
Frequently Asked Questions
16.1.
Can the function memcpy() be used to copy memory?
16.2.
Is memcpy faster than a loop?
16.3.
Does memcpy overwrite memory?
16.4.
How will you handle errors that occur when using memcpy?
16.5.
Are there any alternatives to memcpy() in C ?
16.6.
Can memory blocks that are not adjacent be copied using memcpy()?
16.7.
How well does memcpy() perform when copying data?
17.
Conclusion
Last Updated: Mar 27, 2024
Easy

memcpy() in C

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Hey Ninjas. Are you aware of the memcpy C function? The memcpy function is valuable. Sometimes we need to create a copy of the existing variable or different data types, so here comes the role of memcpy. Copying memory blocks from one location to another can be easier using memcpy(). 

You can avoid copying each element of your code individually. memcpy C can make your code more concise and can save your efforts.

memcpy() in C

In this article, we'll discuss the memcpy C function. We will discuss how it works and can make your code error-prone. So let's discover the memcpy function in depth. So Ninjas, let's explore this topic further.

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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. 

CODE

  • 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;
}

 

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

CODE

  • 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;

 

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. 

CODE

  • 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;
}

 

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.

CODE

  • 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;
}

 

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.

CODE

  • 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;
}

 

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

CODE

  • 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;
}

 

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.

CODE

  • 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;
}

 

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.

CODE

  • 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;
}

 

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.

Pros & Cons of Memcpy() in C

Here are the pros and cons of using memcpy() in C:

Pros

  • 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.

Cons

  • 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.

Does memcpy overwrite memory?

Yes, the memcpy() function in C overwrites memory with the copied data from the source, potentially altering the contents of the destination memory.

How will you handle errors that occur when using memcpy?

Firstly, check for potential errors that might occur. Avoid using null pointers or overlapping memory blocks. Handle the errors appropriately to avoid unexpected results. 

Are there any alternatives to memcpy() in C ?

Yes, there are alternatives to memcpy in C code which include memmove(), strcpy(), and strncpy(). Every function has its limitations. It's essential to choose the correct function according to your need.

Can memory blocks that are not adjacent be copied using memcpy()?

No, it can only copy adjacent memory blocks. The source and destination locations must be adjacent memory blocks to execute the copy.

How well does memcpy() perform when copying data?

The quickest method to copy bytes is memcpy(). However, other forms of copying data might be used in certain situations. For tasks involving general-purpose data copying, memcpy() is a good option.

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.

Happy Coding!

 

Previous article
Noreturn function specifier in C
Next article
exit() vs _Exit()
Live masterclass