cstringmemoryinitializationstrcpy

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


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