using memcpy to copy arrays passed as parameters

2.4k views Asked by At

I want to copy the content of some char-arrays passed as parameters in a function to another char-arrays. So I passed these arrays as pointers (passing by reference). Then I used memcpy to copy the content of these arrays to some other arrays. But the copying-process was not too exact, although I think that I used memcpy correctly. Some characters was deleted, while some new charcters appeared. I tried then to use strcpy, so the content of these arrays was correctly copied. So I want to understand why copying process failed when using memcpy. Here is the some of my code:

struct student{
    bool statusFlag;
    char lastname[20];
    char firstname[20];
    int  mNr;
 };

here is the method:

 struct student getData(char * lastname, char * firstname, int matNr){
     struct student st;
    int i;
    printf("%s\n",lastname);
    if(insertCounter<=size){
        //get data
        st.statusFlag=1;
        memcpy(st.lastname,lastname,strlen(lastname));
        memcpy(st.firstname,firstname,strlen(firstname));
        st.mNr=matNr;
        printf("%s,%s,%d\n",st.lastname,st.firstname,st.mNr);
        return st;
    }else if(insertCounter>size){
       st.statusFlag=0;
        return st;
}    

When I replaced memcpy with strcpy, The copy-operation was successful:

1

There are 1 answers

2
Christopher Ian  Stern On BEST ANSWER

The statement

memcpy(target,source, strlen(source))

should copy all the chars of the string. But, it will stop just short of copying the 0-byte that marks the end of the string. So what you copied won't be a string. This will be a problem if you call any string functions on the new copy (target), basicaly if you use target in any way, you will march off the end, since the end is now unmarked. Probably you will pick up some extra bytes, anything that happens to be in memory after target, worst case you program segfalts if it marches far enough without finding a 0. The function strcpy will copy the 0-byte, I usually use

snprintf(target, sizeof target,  "%s", source); 

Since it does not write past the end of the target buffer, and it always makes room for the 0, protecting against trouble in the next string op.