S
somenath
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
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