Do you think IIT Guwahati certified course can help you in your career?
No
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.
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* a - This destination memory pointer is a pointer to the memory block you wish to copy data to.
const void* b - This 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:
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])));
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.
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.
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;
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; }
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);
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; }
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().
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; }
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.
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; }
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 :
In a multi-threaded application, it helps transfer data between threads.
It is used in graphics programming when copying image or video data.
Data serialization and deserialization in network communication protocols use it.
It can implement queues, stacks, and list-based data structures.
State-saving and state-loading in games are implemented using it.
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.