473,396 Members | 1,915 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Question regarding memcpy and memmove function

Hi All,
I am trying to understand the behavior of the memcpy and memmove.
While doing so I wrote a program as mentioned bellow .

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define SIZE_OF_DST 3
int main(void)
{
char src[]="somenath";
char *dest = malloc(SIZE_OF_DST * sizeof(*dest));
if(dest)
{
memcpy(dest,src,SIZE_OF_DST -1 );
src[SIZE_OF_DST]='\0';
printf("\n Source = %s Destination = %s \n", src,dest);

}
else
{ /*Memory allocation failled */
printf("\n Not enough Memory \n");

}
return 0;
}

Source = som Destination = so

1) But I am not able to understand why "src[SIZE_OF_DST]='\0' " is
affecting the source string?
2) If I remove the "src[SIZE_OF_DST]='\0'" it produce the output as
mentioned as bellow

Source = somenath Destination = so
Please help me to understand this.

I have another couple of questions

1) how "memmove" works for overlapping objects ?
2) Why the behavior of memcpy is undefined for overlapping objects?

3) Is it possible to write strcpy function for overlapping object ?
If yes what would be the logic

..
Regards,
Somenath

Sep 2 '07 #1
14 2764
somenath wrote:
Hi All,
I am trying to understand the behavior of the memcpy and memmove.
While doing so I wrote a program as mentioned bellow .

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define SIZE_OF_DST 3
int main(void)
{
char src[]="somenath";
char *dest = malloc(SIZE_OF_DST * sizeof(*dest));
if(dest)
{
memcpy(dest,src,SIZE_OF_DST -1 );
src[SIZE_OF_DST]='\0';
printf("\n Source = %s Destination = %s \n", src,dest);

}
else
{ /*Memory allocation failled */
printf("\n Not enough Memory \n");

}
return 0;
}

Source = som Destination = so

1) But I am not able to understand why "src[SIZE_OF_DST]='\0' " is
affecting the source string?
Because you told it to? The dest output is pure luck as you didn't
terminate it.
2) If I remove the "src[SIZE_OF_DST]='\0'" it produce the output as
mentioned as bellow

Source = somenath Destination = so
Please help me to understand this.
because you didn't change it.
I have another couple of questions

1) how "memmove" works for overlapping objects ?
Possibly by starting form the last byte and working back. Look for one
on many implementations on the web.
2) Why the behavior of memcpy is undefined for overlapping objects?
Possibly because it makes it easier to optimise, memmove an be used for
overlapping regions
3) Is it possible to write strcpy function for overlapping object ?
If yes what would be the logic
Probably, give it a go and see whet you come up with (hint see 1).

--
Ian Collins.
Sep 2 '07 #2
On Sun, 02 Sep 2007 00:51:22 -0700, somenath wrote:
Hi All,
I am trying to understand the behavior of the memcpy and memmove.
While doing so I wrote a program as mentioned bellow .

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define SIZE_OF_DST 3
int main(void)
{
char src[]="somenath";
char *dest = malloc(SIZE_OF_DST * sizeof(*dest));
if(dest)
{
memcpy(dest,src,SIZE_OF_DST -1 );
src[SIZE_OF_DST]='\0';
printf("\n Source = %s Destination = %s \n", src,dest);

}
else
{ /*Memory allocation failled */
printf("\n Not enough Memory \n");

}
return 0;
}

Source = som Destination = so

1) But I am not able to understand why "src[SIZE_OF_DST]='\0' " is
affecting the source string?
Because src is the source string. You meant dest[SIZE_OF_DST]?
2) If I remove the "src[SIZE_OF_DST]='\0'" it produce the output as
mentioned as bellow

Source = somenath Destination = so
Because dest[3] was already 0. It is very common, but not
guaranteed, for newly allocated memory to be all bits zero.
Please help me to understand this.

I have another couple of questions

1) how "memmove" works for overlapping objects ?
7.21.2.2:
The memmove function copies n characters from the object pointed to by s2 into the
object pointed to by s1. Copying takes place as if the n characters from the object
pointed to by s2 are first copied into a temporary array of n characters that does not
overlap the objects pointed to by s1 and s2, and then the n characters from the
temporary array are copied into the object pointed to by s1.
2) Why the behavior of memcpy is undefined for overlapping objects?
The C99 rationale:
7.21.2 Copying functions
20
A block copy routine should be “right”: it should work correctly even if the blocks being copied
overlap. Otherwise it is more difficult to correctly code such overlapping copy operations, and
portability suffers because the optimal C-coded algorithm on one machine may be horribly slow
on another.
25 A block copy routine should be “fast”: it should be implementable as a few inline instructions
which take maximum advantage of any block copy provisions of the hardware. Checking for
overlapping copies produces too much code for convenient inlining in many implementations.
The programmer knows in a great many cases that the two blocks cannot possibly overlap, so the
space and time overhead are for naught.
30 These arguments are contradictory but each is compelling. Therefore the Standard mandates two
block copy functions: memmove is required to work correctly even if the source and destination
overlap, while memcpy can assume non-overlapping operands and be optimized accordingly.
3) Is it possible to write strcpy function for overlapping object ?
If yes what would be the logic
Copy the source into a temporary buffer. Copy the temporary buffer
into the destination. Beware of buffer overflows.

--
Army1987 (Replace "NOSPAM" with "email")
No-one ever won a game by resigning. -- S. Tartakower

Sep 2 '07 #3
>
Copy the source into a temporary buffer. Copy the temporary buffer
into the destination. Beware of buffer overflows.
I have tried to implement the strcpy for overlapping object as
mentioned bellow.
Is it ok ? please provide your thoughts.

char * safe_strcpy(char *src,char *dest)
{
size_t lengthOfsrc= strlen(src);
char *tempSrc= malloc(lengthOfsrc * sizeof(*tempSrc));
if (!tempSrc)
{
return NULL;
}
else
{/*enough memory available to copy source string to temp string*/
while(*tempSrc++ = *src++)
;
tempSrc = tempSrc -lengthOfsrc - 1 ;
while( *dest++ =*tempSrc++)
;
}
free(tempSrc);
tempSrc = NULL;
return dest;

}

Regards,
Somenath

Sep 2 '07 #4
somenath said:
Hi All,
I am trying to understand the behavior of the memcpy and memmove.
While doing so I wrote a program as mentioned bellow .

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define SIZE_OF_DST 3
int main(void)
{
char src[]="somenath";
char *dest = malloc(SIZE_OF_DST * sizeof(*dest));
if(dest)
{
memcpy(dest,src,SIZE_OF_DST -1 );
src[SIZE_OF_DST]='\0';
I have read the other replies to this article, and several point out
that you meant dest, not src. But unless I've misread, none of them
have pointed out that it should be dest[SIZE_OF_DST - 1], not
dest[SIZE_OF_DST].

If you have N consecutive integer values and the first is 1, then the
last is N. Therefore, if the first is 0, the last is N - 1.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Sep 2 '07 #5
somenath wrote:
>
Hi All,
I am trying to understand the behavior of the memcpy and memmove.
While doing so I wrote a program as mentioned bellow .

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define SIZE_OF_DST 3
int main(void)
{
char src[]="somenath";
char *dest = malloc(SIZE_OF_DST * sizeof(*dest));
if(dest)
{
memcpy(dest,src,SIZE_OF_DST -1 );
src[SIZE_OF_DST]='\0';
printf("\n Source = %s Destination = %s \n", src,dest);

}
else
{ /*Memory allocation failled */
printf("\n Not enough Memory \n");

}
return 0;
}
#include<stdio.h>
#include<string.h>

#define SIZE_OF_DST 3

int main(void)
{
char src[] = "somenath";
char dest[SIZE_OF_DST];

memcpy(dest, src, SIZE_OF_DST - 1);
dest[SIZE_OF_DST - 1] = '\0';
printf("\n Source = %s Destination = %s \n", src, dest);
return 0;
}

--
pete
Sep 2 '07 #6
somenath wrote:
>

Copy the source into a temporary buffer. Copy the temporary buffer
into the destination. Beware of buffer overflows.
I have tried to implement the strcpy for overlapping object as
mentioned bellow.
Is it ok ? please provide your thoughts.

char * safe_strcpy(char *src,char *dest)
{
size_t lengthOfsrc= strlen(src);
char *tempSrc= malloc(lengthOfsrc * sizeof(*tempSrc));
ptr = malloc(N * sizeof *ptr), just simply doesn't
cover every case of allocation.

This is the way to allocate memory for strings,
when you have a length value:

char *tempSrc= malloc(lengthOfsrc + 1);
--
pete
Sep 2 '07 #7
On Sun, 02 Sep 2007 03:29:35 -0700, somenath wrote:
>
>>
Copy the source into a temporary buffer. Copy the temporary buffer
into the destination. Beware of buffer overflows.
I have tried to implement the strcpy for overlapping object as
mentioned bellow.
Is it ok ? please provide your thoughts.

char * safe_strcpy(char *src,char *dest)
{
size_t lengthOfsrc= strlen(src);
char *tempSrc= malloc(lengthOfsrc * sizeof(*tempSrc));
if (!tempSrc)
{
return NULL;
}
else
{/*enough memory available to copy source string to temp string*/
while(*tempSrc++ = *src++)
;
This will copy the terminating null, too. You didn't allocate
space for it.
tempSrc = tempSrc -lengthOfsrc - 1 ;
while( *dest++ =*tempSrc++)
;
}
free(tempSrc);
tempSrc = NULL;
return dest;

}
Try
#define str_move(dest, src) memmove((dest), (src), strlen((src)) + 1)
--
Army1987 (Replace "NOSPAM" with "email")
No-one ever won a game by resigning. -- S. Tartakower

Sep 3 '07 #8
On Mon, 03 Sep 2007 13:07:20 +0200, Army1987 wrote:
Try
#define str_move(dest, src) memmove((dest), (src), strlen((src)) + 1)
I hadn't seen what can happen if src has side effects. But the
point was showing the idea, which can be used unchanged to write a
function. (Or if you *really* want it, capitalize the name of the
macro so that it will be evident that it is a macro, and you'll be
careful not to pass arguments with side effects...)
--
Army1987 (Replace "NOSPAM" with "email")
No-one ever won a game by resigning. -- S. Tartakower

Sep 3 '07 #9
Army1987 wrote:
>
On Mon, 03 Sep 2007 13:07:20 +0200, Army1987 wrote:
Try
#define str_move(dest, src) memmove((dest), (src), strlen((src)) + 1)

I hadn't seen what can happen if src has side effects. But the
point was showing the idea, which can be used unchanged to write a
function. (Or if you *really* want it, capitalize the name of the
macro so that it will be evident that it is a macro, and you'll be
careful not to pass arguments with side effects...)
I think it's best just to forget about str_move,
and write the memmove function call in line, in the source file.
Anybody reading the source code for comprehension
would have to look up str_move and wind up encountering
memmove anyway.

The subject line of this thread is:
Question regarding memcpy and memmove function

.... so, I think that suggesting using memmove directly
would be appropriate.

But I can't understand why using memmove
to implement an overlapping version of strcpy,
wouldn't occur immediately to someone
making a post with that subject line.

--
pete
Sep 3 '07 #10
SM Ryan wrote:
>
pete <pf*****@mindspring.comwrote:

# I think it's best just to forget about str_move,
# and write the memmove function call in line, in the source file.
# Anybody reading the source code for comprehension
# would have to look up str_move and wind up encountering
# memmove anyway.

With little effort you can expand that to a general
prohibition against typedefs and functions, because
in both cases you have to go look up the definitions.
Concerning this macro:
#define str_move(dest, src) memmove((dest), (src), strlen((src)) + 1)

my opinion was that
memmove(dest, src, strlen(src) + 1)
wasn't any less cryptic than
str_move(dest, src)
and I didn't see any other purpose to this particular macro,
other than to attempt to make the code easier to read.
--
pete
Sep 4 '07 #11
On Sep 2, 6:26 pm, pete <pfil...@mindspring.comwrote:
somenath wrote:
Copy the source into a temporary buffer. Copy the temporary buffer
into the destination. Beware of buffer overflows.
I have tried to implement the strcpy for overlapping object as
mentioned bellow.
Is it ok ? please provide your thoughts.
char * safe_strcpy(char *src,char *dest)
{
size_t lengthOfsrc= strlen(src);
char *tempSrc= malloc(lengthOfsrc * sizeof(*tempSrc));

ptr = malloc(N * sizeof *ptr), just simply doesn't
cover every case of allocation.

This is the way to allocate memory for strings,
when you have a length value:

char *tempSrc= malloc(lengthOfsrc + 1);
I have changed my code as bellow . I was trying to test one
scenario . But i am not sure if the program is working
properly .Please provide some inputs

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char * safe_strcpy(char *src,char *dest)
{
size_t lengthOfsrc= strlen(src);
char *tempSrc= malloc(lengthOfsrc + 1); /*this line is changed*/
if (!tempSrc)
{
return NULL;
}
else
{/*enough memory available to copy source string to temp string*/
while(*tempSrc++ = *src++)
;
tempSrc = tempSrc -lengthOfsrc - 1 ;
while( *dest++ =*tempSrc++)
;
}
free(tempSrc);
tempSrc = NULL;
return dest;

}
int main(void)
{
char msg[] = "hello, world!";
char *ptr = &msg[6];

char src[] = "somenath";

safe_strcpy(msg,ptr);
// strcpy(msg,ptr);
puts(msg);
return 0;
}

Output :
hello,hello, world!

is it correct ?

Regards,
Somenath

Sep 4 '07 #12
On Mon, 03 Sep 2007 21:12:00 -0700, somenath <so*********@gmail.com>
wrote:
>On Sep 2, 6:26 pm, pete <pfil...@mindspring.comwrote:
>somenath wrote:
Copy the source into a temporary buffer. Copy the temporary buffer
into the destination. Beware of buffer overflows.
I have tried to implement the strcpy for overlapping object as
mentioned bellow.
Is it ok ? please provide your thoughts.
char * safe_strcpy(char *src,char *dest)
Most of the standard copy functions have the destination as the first
argument.
{
size_t lengthOfsrc= strlen(src);
char *tempSrc= malloc(lengthOfsrc * sizeof(*tempSrc));

ptr = malloc(N * sizeof *ptr), just simply doesn't
cover every case of allocation.

This is the way to allocate memory for strings,
when you have a length value:

char *tempSrc= malloc(lengthOfsrc + 1);

I have changed my code as bellow . I was trying to test one
scenario . But i am not sure if the program is working
properly .Please provide some inputs

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char * safe_strcpy(char *src,char *dest)
{
size_t lengthOfsrc= strlen(src);
char *tempSrc= malloc(lengthOfsrc + 1); /*this line is changed*/
if (!tempSrc)
{
return NULL;
}
else
{/*enough memory available to copy source string to temp string*/
while(*tempSrc++ = *src++)
;
tempSrc = tempSrc -lengthOfsrc - 1 ;
while( *dest++ =*tempSrc++)
;
}
free(tempSrc);
tempSrc = NULL;
Since tempSrc will cease to exist after the next statement, this
assignment is kind of a waste.
return dest;

}
int main(void)
{
char msg[] = "hello, world!";
char *ptr = &msg[6];

char src[] = "somenath";
It is good to be proud of your name but is it worth three blank lines
before and one after, especially since you don't use it. I suspect
you included this solely to suppress, not actually fix, an error
uncovered during testing.
>
safe_strcpy(msg,ptr);
Inside safe_strcpy:
src is set to &msg[0].
dest is set to &msg[6].
lengthofSrc is set to 13.
malloc succeeds and tempSrc holds the address of a 14 byte
block.
14 bytes are copied from msg++ to tempSrc++.
tempSrc is reset back to start of 14 byte block.
An attempt is made to copy 14 bytes from tempSrc++ to dest++.
As part of copying the eighth byte, dest is incremented beyond
the end of msg. This invokes undefined behavior as does all further
attempts to store into the byte dest points to.
// strcpy(msg,ptr);
puts(msg);
return 0;
}

Output :
hello,hello, world!

is it correct ?
safe_strcpy may be OK but main calls it in a manner that invokes
undefined behavior. msg needs to be an array of at least 20 bytes.
Remove del for email
Sep 4 '07 #13
somenath wrote:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char * safe_strcpy(char *src,char *dest)
{
size_t lengthOfsrc= strlen(src);
char *tempSrc= malloc(lengthOfsrc + 1); /*this line is changed*/
if (!tempSrc)
{
return NULL;
}
else
{/*enough memory available to copy source string to temp string*/
while(*tempSrc++ = *src++)
;
tempSrc = tempSrc -lengthOfsrc - 1 ;
while( *dest++ =*tempSrc++)
;
}
free(tempSrc);
You're freeing (original tempSrc + lengthOfsrc + 1)
instead of (original tempSrc).
tempSrc = NULL;
return dest;

}
int main(void)
{
char msg[] = "hello, world!";
You don't have enough room in msg to do what you want.
char *ptr = &msg[6];

char src[] = "somenath";
Get rid of src.
>
safe_strcpy(msg,ptr);
// strcpy(msg,ptr);
puts(msg);
return 0;
}
/* BEGIN new.c */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *safe_strcpy(char *src, char *dest);

int main(void)
{
char msg[] = "hello, world!\0hello, world!";
char *ptr = &msg[6];

if (safe_strcpy(msg, ptr) == NULL) {
puts("safe_strcpy(msg, ptr) == NULL");
}
puts(msg);
return 0;
}

char *safe_strcpy(char *src, char *dest)
{
char *const buff = malloc(strlen(src) + 1);
char *buff_ptr = buff;

if (buff == NULL) {
return NULL;
} else {
while ((*buff_ptr++ = *src++) != '\0') {
;
}
buff_ptr = buff;
while ((*dest++ = *buff_ptr++) != '\0') {
;
}
}
free(buff);
return dest;
}

/* END new.c */
--
pete
Sep 4 '07 #14
On Sep 4, 2:54 pm, pete <pfil...@mindspring.comwrote:
somenath wrote:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char * safe_strcpy(char *src,char *dest)
{
size_t lengthOfsrc= strlen(src);
char *tempSrc= malloc(lengthOfsrc + 1); /*this line is changed*/
if (!tempSrc)
{
return NULL;
}
else
{/*enough memory available to copy source string to temp string*/
while(*tempSrc++ = *src++)
;
tempSrc = tempSrc -lengthOfsrc - 1 ;
while( *dest++ =*tempSrc++)
;
}
free(tempSrc);

You're freeing (original tempSrc + lengthOfsrc + 1)
instead of (original tempSrc).
tempSrc = NULL;
return dest;
}
int main(void)
{
char msg[] = "hello, world!";

You don't have enough room in msg to do what you want.
char *ptr = &msg[6];
char src[] = "somenath";

Get rid of src.
safe_strcpy(msg,ptr);
// strcpy(msg,ptr);
puts(msg);
return 0;
}

/* BEGIN new.c */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *safe_strcpy(char *src, char *dest);

int main(void)
{
char msg[] = "hello, world!\0hello, world!";
char *ptr = &msg[6];

if (safe_strcpy(msg, ptr) == NULL) {
puts("safe_strcpy(msg, ptr) == NULL");
}
puts(msg);
return 0;

}

char *safe_strcpy(char *src, char *dest)
{
char *const buff = malloc(strlen(src) + 1);
char *buff_ptr = buff;

if (buff == NULL) {
return NULL;
} else {
while ((*buff_ptr++ = *src++) != '\0') {
;
}
buff_ptr = buff;
while ((*dest++ = *buff_ptr++) != '\0') {
;
}
}
free(buff);
return dest;

}

/* END new.c */
Many thanks for providing inputs.
Sep 4 '07 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: franky.backeljauw | last post by:
Hello, following my question on "std::copy versus pointer copy versus member copy", I had some doubts on the function memcpy, as was used by tom_usenet in his reply. - Is this a c++ standard...
2
by: rinku24 | last post by:
What is the difference between memcpy and memmove? Which is more expensive?
7
by: bisforbenson | last post by:
I'm trying to compile things with gcc 4. After running the following command: % gcc -O3 -g -Wall -Wno-unused -DLINUX -D_REENTRANT -o ../../obj/egi.o -I../../include/ -I... -c egi.cpp i get...
21
by: Mac | last post by:
$ cat junk27.c #include <stdio.h> #include <string.h> int main (void) { printf("The difference between memcpy and memmove is %ld\n", (long int) memcpy - (long int) memmove); return 0; }
35
by: Christopher Benson-Manica | last post by:
(if this is a FAQ or in K&R2, I didn't find it) What parameters (if any) may be 0 or NULL? IOW, which of the following statements are guaranteed to produce well-defined behavior? char src;...
9
by: Alfonso Morra | last post by:
Hi, I am having some probs with copying memory blocks around (part of a messaging library) and I would like some confirmation to make sure that I'm going about things the right way. I have...
6
by: novice | last post by:
Please explain with an example whts the DIFFERENCE between "memcpy" and "memmove"
5
by: xdevel | last post by:
Hi, anyone can make me an example where memmove does not cause a memory overlapping and where memcpy do it? Thanks
8
by: mthread | last post by:
Hi, I am copying data from one buffer(this data is a binary data not string) to another buffer. Earlier when I used C, I used the memcpy function call to copy the values. Is there any equivalent...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.