Memcpy Char Pointers

17,315

Solution 1

char * concat(const char * first, const char * second)
{
    int lf = strlen(first);
    int ls = strlen(second);
    int len = lf + ls;
    char * rb = new char[len+1];//You need this +1 here
    memcpy(rb, first, lf);
    memcpy(rb+lf, second, ls);
    rb[len] = 0;
    return rb;
}
int main ()
{
    char *first = new char[10], *second=new char[10];
    strcpy(first, "first");//This is an unsafe way. You can take the value from anywhere possible
    strcpy(second, "second");//This is an unsafe way. You can take the value from anywhere possible
    char * third = concat(first, second);
    cout <<  third << endl;//Don't use cout << concat(first, second) << endl; since it leads to a emory leak
    delete [] third;
    return 0;
}

You can't concatenate two string without using extra memory, since every time you need a memory block of size of the sum +1 (or more) of the two given strings.

Solution 2

Your memcpy is equivalent to memcpy ("Hello ", second, strlen(second)+1);. Copying into a constant is (on some platforms, apparently including yours) an access violation.

    char *first = new char[10], *second=new char[10]; 
    first="Hello ";

First you make first point to some memory you allocated. Then you throw that pointer away and make it point to a static string. That's not what you mean. Maybe you meant:

    strcpy (first, "Hello ");

This copies the constant's data into the space first points to.

Solution 3

Change

scanf("%s", &first);

to

scanf("%s", first);

You access the wrong memory when scaning.

Share:
17,315
Tanatos Daniel
Author by

Tanatos Daniel

Updated on June 25, 2022

Comments

  • Tanatos Daniel
    Tanatos Daniel almost 2 years

    I have this simple program in which I want to concatenate two char pointers using memcpy, but I get access violation reading location on the memcpy line.

    char *first = new char[10], *second=new char[10]; 
    first="Hello ";
    printf("\second: ");
    scanf("%s",&second);
    memcpy(first,second,strlen(second)+1);
    printf ("Result: %s\n", first);
    

    Because copying into a constant gets me the violation, I tried this:

    char *first = new char[20], *second="world!"; 
    printf("first: ");
    scanf("%s",&first);
    memcpy(first,second,strlen(second)+1);
    printf ("Result: %s\n", first);
    

    which gets me access violation writing location. How should I concatenate correctly the two pointers?