I am attempting to develop a method to customize strcpy
. I considered two approaches for this implementation. One method involves using memcpy
, while the other involves incrementing the pointer and assigning the value.
Implementation using memcpy
worked as expected. Code snippet is pasted below.
#include <stdio.h>
#include <string.h>
void mystrcpy(void *dest, void *src, size_t size)
{
memcpy((char*)dest,(char*)src,size);
printf("Final - %sn",(char*)dest);
}
int main()
{
char *src = "ABC";
char dest[20];
printf("%p %pn",src,dest);
mystrcpy(dest,src,sizeof(src));
return 0;
}
Output is below:
000000000040400C 000000000061FE00
Final - ABC
Hence, I had gone for the second implementation and it is not fully completed. Since I’m just getting started, I saw some behavior that wasn’t what I had anticipated. I am not sure about this. May be I am lagging some very important concepts here.
Here, I consider taking two void*
parameters for source and destination. Something similar to below.
void mystrcpy(void *dest, void *src)
Pasting my code below,
#include <stdio.h>
#include <stdint.h>
void mystrcpy(void *dest, void *src)
{
char *_dest = (char*)dest;
char *_src = (char*)src;
*_dest = *_src;
printf("%c %cn",*_src,*_dest);
printf("%p %pn",_src,_dest);
_src++ ; _dest++;
*_dest = *_src;
printf("%c %cn",*_src,*_dest);
printf("%p %pn",_src,_dest);
_src++ ; _dest++;
*_dest = *_src;
printf("%c %cn",*_src,*_dest);
printf("%p %pn",_src,_dest);
_src++ ; _dest++;
*_dest = '';
printf("Final - %d %d %d %p %p %pn",_dest[0],_dest[1],_dest[2],&_dest[0],&_dest[1],&_dest[2]);
}
int main()
{
char *src = "ABC";
char dest[20];
printf("%p %pn",src,dest);
mystrcpy(dest,src);
return 0;
}
And the output shows
0000000000404034 000000000061FE00
A A
0000000000404034 000000000061FE00
B B
0000000000404035 000000000061FE01
C C
0000000000404036 000000000061FE02
Final – 0 0 0 000000000061FE03 000000000061FE04 000000000061FE05
It was copying the value as expected. I am just confused on the last print,
how it went to xxx03 xxx04 xxx05 instead of xxx00 xxx01 xxx03 !!. And this is the reason why I got garbage value when I printed the _dest
.
Please share your thoughts on this.
Thanks in advance.