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

72 Views Asked by At

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 becomes an initialised string with the same length and content as another_string.

3

There are 3 best solutions below

0
Steve Summit On BEST ANSWER

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 allocated) */

char *my_string_10 = malloc(20);
free(my_string_10);
strcpy(my_string_10, another_string);    /* INVALID (no longer allocated) */

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

char *my_string_11 = exceptionally_bad_allocator();
strcpy(my_string_11, another_string);    /* INVALID (not validly allocated) */
1
0___________ On

It is not possible using strcpy but it is possible to write your own function

//if buff is NULL then it will allocate memory for it.
char *strcpyalloc(char *buff, const char *src)
{
    size_t len;
    if(!buff)  // if not allocated allocate
    {
        len = strlen(src) + 1;
        buff = malloc(len);
        if(buff)
        {
            memcpy(buff, src, len);
        }
    }
    else strcpy(buff, src);
    return buff;
}


int main(void)
{
    char *str = NULL;

    str = strcpyalloc(str, "Hello World!");
    if(str) printf("\"%s\"\n", str);
    free(str);
}

https://godbolt.org/z/Me4GEr5dP

0
chux - Reinstate Monica On

When variable length arrays VLA are supported, code can create right-sized space that is valid until the end of the block.

{
  char my_string[strlen(another_string) + 1];
  strcpy(my_string, another_string);
  ...
  // No need to free `my_string`
}