1

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);
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
user157629
  • 624
  • 4
  • 17
  • Neither option is correct. The second allocates one too few bytes, and contains a meaningless cast from size_t to int which may lose information, and uses `sizeof(char)` which is guaranteed to be 1. It also has the source and destination the wrong way round. You may wish to find out how to enable undefined behavior sanitization in your compiler. – Paul Hankin Dec 09 '20 at 10:47
  • I edited the question fixing the strcpy error – user157629 Dec 09 '20 at 10:54
  • 1
    @user157629 don't edit your question if it invalidates existing answers – Jabberwocky Dec 09 '20 at 10:57

1 Answers1

2

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 );
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335