Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to create a character array within a strcpy?

Is it possible to copy a string using C’s strcpy without first assigning memory to a char *character_array?

Basically, is something like this possible:

strcpy(char *my_string, another_string);

where my_string is an initialised string with the same length and content as another_string.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

strcpy never allocates memory. The destination must be a pointer to enough, writable, validly-allocated memory, and you are responsible for making sure that the destination memory is validly allocated, long enough, and writable.

So these are all okay:

char *another_string = "hello";
char my_string_1[20];
strcpy(my_string_1, another_string);     /* valid (plenty of space) */

char my_string_2[6];
strcpy(my_string_2, another_string);     /* valid (just enough space) */

char my_string_3[] = "world";
strcpy(my_string_2, another_string);     /* valid (just enough space) */

char buf[6];
char *my_string_4 = buf;
strcpy(my_string_4, another_string);     /* valid (via intermediate pointer) */

char *my_string_5 = malloc(6);
strcpy(my_string_5, another_string);     /* valid (assuming malloc succeeds) */

char *my_string_6 = malloc(strlen(another_string) + 1);
strcpy(my_string_6, another_string);     /* valid (assuming malloc succeeds) */

But these are not valid:

char my_string_7[5];
strcpy(my_string_7, another_string);     /* INVALID (not enough space) */

char *my_string_8 = "world";
strcpy(my_string_8, another_string);     /* INVALID (destination not writable) */

char *my_string_9;
strcpy(my_string_9, another_string);     /* INVALID (destination not initialized) */

char *exceptionally_bad_allocator()
{
    char local_buffer[20];
    return local_buffer;
}

char *my_string_10 = exceptionally_bad_allocator();
strcpy(my_string_10, another_string);    /* INVALID (destination not validly allocated) */
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading