Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memcpy Char Pointers

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?

like image 526
Tanatos Daniel Avatar asked Dec 01 '22 16:12

Tanatos Daniel


2 Answers

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.

like image 146
David Schwartz Avatar answered Dec 25 '22 23:12

David Schwartz


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.

like image 35
Doonyx Avatar answered Dec 25 '22 22:12

Doonyx