user157629
user157629

Reputation: 634

Can I strcpy a char pointer into another without allocating the second one?

I want to copy one char * string into another char * variable so I have the same string stored twice into those two char * variables but that they do not depend on each other, so if I make a free of the first one, I don't lose the data on the second one.

My question is, can I just execute the strcpy without allocating the second char * string? Is any of the following options correct / incorrect?

Option 1

//char *string_1 is already allocated and contains a valid string
char *string_2;

strcpy(string_1, string_2);

printf("%s", string_2);

Option 2

//char *string_1 is already allocated and contains a valid string
char *string_2;

string_2 = malloc(((int) strlen(string_1)) * sizeof(char));

strcpy(string_1, string_2);

printf("%s", string_2);

Upvotes: 1

Views: 368

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

In the both options there shall be

strcpy(string_2, string_1);

instead of

strcpy(string_1, string_2);

Both options are incorrect.

In the first option there is no allocated memory where you are going to copy a string and the pointer string_2 does not point to such a memory.

char *string_2;

The second option is incorrect because you allocated not enough memory. Instead of

string_2 = malloc(((int) strlen(string_2)) * sizeof(char));

where there is a typo that is instead of strlen( string_2 ) there shall be strlen( string_1 ) you have to write at least

string_2 = malloc( ( strlen(string_1) + 1 ) * sizeof(char));

or just

string_2 = malloc( strlen(string_1) + 1 );

Upvotes: 2

Related Questions