-1

I have the following set of code not able to find why I am getting garbage value.My intention is to copy the number of byte as destination irrespective of source to make a generic copy for my application. But not getting the correct result.Is there any way to achieve this.

int main()
{
    char x[6];
    char *i="pra";
    memset(&x,0,6); //Doing memset

    memcpy(&x,i,6);
    printf("%x %x %x %x %x %x",x[0],x[1],x[2],x[3],x[4],x[5]);
}

o/p:
70 72 61 0 25 78

We can see the output after 0 is garbage.But why it is comming and where it is comming. whey memset not working properly. Pleae help to get the cause of this concept.

pradipta
  • 1,718
  • 2
  • 13
  • 24

3 Answers3

6

You're copying six bytes from i to x, but only have four bytes of non-garbage values in i, so the last two are whatever happened to be after i.

amalloy
  • 89,153
  • 8
  • 140
  • 205
2

You are copying 6 bytes of i while its length is 4. Doing that will solve the problem:

memcopy(&x, i, strlen(i));
Nicop
  • 314
  • 1
  • 6
  • In that case if the x is smaller than the source then undefined behavior will be the result – pradipta Jul 03 '14 at 05:33
  • 1
    1) it's `memcpy`; 2) this will needlessly walk `i` twice and won't NUL-terminate `x`. – Matteo Italia Jul 03 '14 at 05:35
  • 2
    @MatteoItalia is right. That's exactly the purpose `strcpy()` and `strncpy()` have been invented for. – glglgl Jul 03 '14 at 05:36
  • 1
    You can do a *MIN(strlen(i) + 1, 6)* where the min macro can be found [here](http://stackoverflow.com/questions/3437404/min-and-max-in-c) – Nicop Jul 03 '14 at 05:38
  • Thanks Nicop,Yes I also though this to do..It will give a way to copy generic way. – pradipta Jul 03 '14 at 05:42
  • @glglgl: careful, `strncpy` is an unfortunate historic accident, and does not do what most people think it does (most importantly, it won't terminate the buffer if the source string is as big as the buffer). – Matteo Italia Jul 03 '14 at 05:49
  • @MatteoItalia Right, but it is possible to cope with that (just manually add a `'\0'` and give `strncpy()` a number reduced by 1). – glglgl Jul 03 '14 at 05:51
2

memset() is working properly. But memcpy() coping junk data to buffer.

int main()
{
    char x[6];
    char *i="pra";
    memset(&x,0,6); //Doing memset
    printf("%x %x %x %x %x %x",x[0],x[1],x[2],x[3],x[4],x[5]); // All will be 0 here
    memcpy(&x,i,6); //6 bytes here mentioned is reponsible for that values
    printf("%x %x %x %x %x %x",x[0],x[1],x[2],x[3],x[4],x[5]);
}
Jeyaram
  • 9,158
  • 7
  • 41
  • 63