Using memset(), memcpy(), and memmove() in C

By: Emiley J Emailed: 1729 times Printed: 2328 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The memset() Function

To set all the bytes in a block of memory to a particular value, use memset(). The function prototype is

void * memset(void *dest, int c, size_t count);

The argument dest points to the block of memory. c is the value to set, and count is the number of bytes, starting at dest, to be set. Note that while c is a type int, it is treated as a type char. In other words, only the low-order byte is used, and you can specify values of c only in the range 0 through 255.

Use memset() to initialize a block of memory to a specified value. Because this function can use only a type char as the initialization value, it is not useful for working with blocks of data types other than type char, except when you want to initialize to 0. In other words, it wouldn't be efficient to use memset() to initialize an array of type int to the value 99, but you could initialize all array elements to the value 0. memset() will be demonstrated in program below.

The memcpy() Function

memcpy() copies bytes of data between memory blocks, sometimes called buffers. This function doesn't care about the type of data being copied--it simply makes an exact byte-for-byte copy. The function prototype is

void *memcpy(void *dest, void *src, size_t count);

The arguments dest and src point to the destination and source memory blocks, respectively. count specifies the number of bytes to be copied. The return value is dest. If the two blocks of memory overlap, the function might not operate properly--some of the data in src might be overwritten before being copied. Use the memmove() function, discussed next, to handle overlapping memory blocks. memcpy() will be demonstrated in program below.

The memmove() Function

memmove() is very much like memcpy(), copying a specified number of bytes from one memory block to another. It's more flexible, however, because it can handle overlapping memory blocks properly. Because memmove() can do everything memcpy() can do with the added flexibility of dealing with overlapping blocks, you rarely, if ever, should have a reason to use memcpy(). The prototype is

void *memmove(void *dest, void *src, size_t count);

dest and src point to the destination and source memory blocks, and count specifies the number of bytes to be copied. The return value is dest. If the blocks overlap, this function ensures that the source data in the overlapped region is copied before being overwritten. Sample program below demonstrates memset(), memcpy(), and memmove().

A demonstration of memset(), memcpy(), and memmove().

1: /* Demonstrating memset(), memcpy(), and memmove(). */
2:
3: #include <stdio.h>
4: #include <string.h>
4:
5: char message1[60] = "Four score and seven years ago ...";
6: char message2[60] = "abcdefghijklmnopqrstuvwxyz";
7: char temp[60];
8:
9: main()
10: {
11:    printf("\nmessage1[] before memset():\t%s", message1);
12:    memset(message1 + 5, `@', 10);
13:    printf("\nmessage1[] after memset():\t%s", message1);
14:
15:    strcpy(temp, message2);
16:    printf("\n\nOriginal message: %s", temp);
17:    memcpy(temp + 4, temp + 16, 10);
18:    printf("\nAfter memcpy() without overlap:\t%s", temp);
19:    strcpy(temp, message2);
20:    memcpy(temp + 6, temp + 4, 10);
21:    printf("\nAfter memcpy() with overlap:\t%s", temp);
22:
23:    strcpy(temp, message2);
24:    printf("\n\nOriginal message: %s", temp);
25:    memmove(temp + 4, temp + 16, 10);
26:    printf("\nAfter memmove() without overlap:\t%s", temp);
27:    strcpy(temp, message2);
28:    memmove(temp + 6, temp + 4, 10);
29:    printf("\nAfter memmove() with overlap:\t%s\n", temp);
30:
31: }
message1[] before memset():     Four score and seven years ago ...
message1[] after memset():      Four @@@@@@@@@@seven years ago ...
Original message: abcdefghijklmnopqrstuvwxyz
After memcpy() without overlap: abcdqrstuvwxyzopqrstuvwxyz
After memcpy() with overlap:    abcdefefefefefefqrstuvwxyz
Original message: abcdefghijklmnopqrstuvwxyz
After memmove() without overlap:        abcdqrstuvwxyzopqrstuvwxyz
After memmove() with overlap:   abcdefefghijklmnqrstuvwxyz

ANALYSIS: The operation of memset() is straightforward. Note how the pointer notation message1 + 5 is used to specify that memset() is to start setting characters at the sixth character in message1[] (remember, arrays are zero-based). As a result, the 6th through 15th characters in message1[] have been changed to @.

When source and destination do not overlap, memcpy() works fine. The 10 characters of temp[] starting at position 17 (the letters q through z) have been copied to positions 5 though 14, where the letters e though n were originally located. If, however, the source and destination overlap, things are different. When the function tries to copy 10 characters starting at position 4 to position 6, an overlap of 8 positions occurs. You might expect the letters e through n to be copied over the letters g through p. Instead, the letters e and f are repeated five times.

If there's no overlap, memmove() works just like memcpy(). With overlap, however, memmove() copies the original source characters to the destination.


DO use memmove() instead of memcpy() in case you're dealing with overlapping memory regions.

DON'T try to use memset() to initialize type int, float, or double arrays to any value other than 0.



C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(41)


1. View Comment

Very good !!

View Tutorial          By: SGK at 2009-04-26 23:53:44
2. View Comment

Its really good and helpfull..........
cheers
sumit


View Tutorial          By: sumit at 2009-04-28 05:17:17
3. View Comment

helpfull !!!!

View Tutorial          By: Anonymous at 2009-05-12 03:48:15
4. View Comment

Awesome .
Helpfull!!


View Tutorial          By: ARMLAB-NG at 2009-06-06 09:22:00
5. View Comment

Thanks that made this concept of memory very cleat...cheers

View Tutorial          By: Tarak at 2009-06-24 07:58:04
6. View Comment

it was very helpful to fix one obscure bug

View Tutorial          By: ander13 at 2009-06-30 04:51:47
7. View Comment

Helpful..........

Good


View Tutorial          By: Ravi at 2009-07-03 07:08:56
8. View Comment

realy good explanation

View Tutorial          By: pandit at 2009-07-19 11:24:55
9. View Comment

Thanks a lot.. it made my concepts of memmove,memset and memcpy absolutely clear.. gr8 explanation

View Tutorial          By: Rimmi Jain at 2009-07-23 06:42:01
10. View Comment

Good and very clear explanation...

View Tutorial          By: Pavana at 2010-01-05 23:35:30
11. View Comment

It's Very Nice. Particularly:
DO use memmove() instead of memcpy() in case you're dealing with overlapping memory regions.

DON'T try to use memset() to initialize type int, float, or double arrays to any value other than 0.


View Tutorial          By: Rasmi Ranjan Nayak at 2010-01-12 04:40:18
12. View Comment

Very clearly explained...

View Tutorial          By: Bina at 2010-04-08 06:56:37
13. View Comment

This example is very good, but it doesnt work in Microsoft visual studio 2005. In that memcpy will exactly work as memmove.

View Tutorial          By: soma at 2010-04-13 04:34:00
14. View Comment

Very good explanation specially overlapped memory block.

View Tutorial          By: MANISH RASTOGI at 2010-06-22 05:44:07
15. View Comment

Very good tutorial, but I have a small question here:
Why does the three functions have a return value, which is void* that return the source pointer again???. It adds no value to return the address of the source buffer while I supply it in the function call...


View Tutorial          By: Mohammad NABIL at 2010-07-20 05:58:19
16. View Comment

Excellent.
Just one question... What is the reason for the number of bytes to be of type size_t? Is it a typedef of int? If yes, why not just use int?


View Tutorial          By: HeilGates at 2010-08-04 13:38:12
17. View Comment

To 15:
Sometimes it is useful to return the same address passed in the parameters and the developer should think what parameter he should return.
The common case occur when you want to chain the result of a function inside another function like: strcat(strcpy(buf, "hi "), "friend");
The strcpy function returns the same address of buf, as memcpy does. If strcpy did not return buf address, you should store this value elsewhere before use strcat.

Think of this another situation:
return memcpy(malloc(sizeof(int)), &number, 4)
You use malloc directly inside the memcpy function and has no source pointer stored in a variable. So, in this case, you would need the return value of memcpy.


View Tutorial          By: Anderson Goulart at 2010-08-24 19:15:14
18. View Comment

Hello friends can anybody tell me how to assign integer value into the pointer instead of assigning address of a variable to it?

View Tutorial          By: gnvkdramesh at 2010-09-10 04:27:46
19. View Comment

Neatly explained about the three important function. But where we can use memcpy() and memmove() as per the implementation in our program.

View Tutorial          By: Jitendra Lenka at 2011-02-03 06:34:10
20. View Comment

could somebody please tell a case where memcpy() will not give the desired output, but memmove() will do.

View Tutorial          By: freak at 2011-02-09 20:29:26
21. View Comment

Really nice explanation...
nice to understand...


View Tutorial          By: Parth Kansara at 2011-06-21 02:11:52
22. View Comment

thnx

View Tutorial          By: Prakash at 2011-07-27 03:05:17
23. View Comment

I have initialized a int array while declaring.
Now I wanted to reinitialize the int array in middle of the code.
How can I proceed. Can anyone please help me on this.

Thanks alot in advance!!!


View Tutorial          By: Prashanth at 2011-09-15 11:16:40
24. View Comment

ans to 23:
by using gdb(GNU debugger) tool we can set break points up to where u want to reinitialize the array set break point and initialize with new values simple>>>>>>>>>

okkkkkkkkk


View Tutorial          By: Bhargav at 2011-11-02 13:23:51
25. View Comment

Out of -1, 0, and 1 which one can I use as second parameter to memset. Please reply immediately.

View Tutorial          By: Sanjay Bhosale at 2011-12-06 13:17:54
26. View Comment

To 25
void *memset( void *buffer, int ch, size_t count );

The function memset() copies ch into the first count characters of buffer, and returns buffer. memset() is useful for intializing a section of memory to some value. For example, this command:
memset( the_array, '\0', sizeof(the_array) );

is a very efficient way to set all values of the_array to zero.

Basically memset() is used while initialing array of characters or string.


View Tutorial          By: Doniv at 2011-12-15 10:10:52
27. View Comment

I did not get the same result for memcpy - e and f are not repeated 5 times. I got this one:
"After memcpy() with overlap: abcdefefefijklmnqrstuvwxyz."
Why? I am not sure memcpy copies byte-by-bytes in this case. Could you explain to me, please?


View Tutorial          By: dml at 2012-01-02 13:32:20
28. View Comment

very useful...!

View Tutorial          By: mahesh at 2012-01-06 09:55:59
29. View Comment

hello it wrong in memmove nd memcpy case. I am getting different answers for memmove which you gave. Please check it and give me the correct explanation. I am getting same output for both memcpy and memmove. Please correct me if i am wrong

View Tutorial          By: jaya at 2012-04-05 17:18:14
30. View Comment

very nice..!

View Tutorial          By: neeraj at 2012-04-21 11:12:08
31. View Comment

Nice Explanation.....

View Tutorial          By: Vinoth at 2012-06-20 09:37:21
32. View Comment

Excellent !!!
Never thought about it...


View Tutorial          By: RahulC at 2012-07-03 11:36:57
33. View Comment

Does memmove care if the source is bytes and the dest is int? (or vise versa) The # of bytes are the same in both but the # of locations in each array is different.

Thanks...


View Tutorial          By: Paul at 2012-07-20 11:59:32
34. View Comment

Really nice tutorial for memset(), memcopy() and memmove(),,,,!!!
Nicely explained !!!


View Tutorial          By: Hitesh Kumar at 2012-09-03 09:16:32
35. View Comment

Hi,
Very Nice explanation ,I tried both memcpy() & memmove() ,But both are working same there is no any difference in the output in case of overlapping .

As you shown the output after memcpy() in case of overlapping , It does the runtime copy.


View Tutorial          By: Harsh Verma at 2013-01-30 13:43:05
36. View Comment

awesome.........

View Tutorial          By: tar at 2013-03-14 07:36:56
37. View Comment

thumbs up!

View Tutorial          By: huang at 2013-03-28 04:02:33
38. View Comment

Well explained. Example clear out the diff

View Tutorial          By: sonam at 2014-06-25 19:05:20
39. View Comment

my requirement is i have a source string as src{"adc ok 1,xxx"}
destination is also a buffer,

what i want is to copy the src string from x to end in dest buffer, here x is 3 bytes but its size is not fixed in my requirement it may b 2 or 3 or 4 . please help me


View Tutorial          By: Anil at 2014-10-27 08:36:23
40. View Comment

What happens if applied to an integer array?

View Tutorial          By: SHUVO at 2015-07-01 21:14:16
41. View Comment

Thanks...

View Tutorial          By: SHUVO at 2015-07-01 21:20:47

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Emiley J
Password must include both numeric and alphabetic characters - Magento
What is Hadoop?
Returning multiple values from a web service
Tomcat and httpd configured in port 8080 and 80
Java Webservices using Netbeans and Tomcat
Java WebService connected to Database
How to Deploy a Java Web Service
Call a webservice in Java
Java WebService - Create your first web service in Java
package javax.jws does not exist
Getting Started with Android
HTML5 Location - getCurrentPosition() in HTML5
HTML5 Canvas - Using Canvas in HTML5
HTML5 - Introduction
HTML5 Video - Handling video in HTML5

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Using memset(), memcpy(), and memmove() in C
lseek() sample program in C
perror() Function - example program in C
UNIX read and write system calls sample program in C
assert() Function Example program in C
Find square and square root for a given number in C
Printing a simple histogram in C
Arrays of Structures example program in C
Listing Files and Directories sample program in C
scanf and sscanf sample program in C
Character Arrays in C
External Variables and Scope in C
goto and labels in C
Open, Creat, Close, Unlink system calls sample program in C
Using calloc() Function in C
Most Emailed Articles (in C)
scanf and sscanf sample program in C
Line Counting sample program in C
union example program in C
Variables and Arithmetic Expressions in C
Assignment Operators and Expressions in C
Command-line Arguments in C
Error Handling - Stderr and Exit - sample program in C
A Storage Allocator sample program in C
Using memset(), memcpy(), and memmove() in C
Writing The First C program
Infix to Prefix And Postfix in C
Getting Started with C
File Copying in C
Arrays sample program in C
Constants and escape sequences in C