Search code examples
cpointersc-stringsstring-literalsstrdup

What is the diffrence between char *str="this is a string" from char *str = strdup("this is a string") in C


What's the difference between the following code :

char* str = "this is a string"

From this one :

char* str = strdup("this is a string")

The usage scenarios ?


Solution

  • In this declaration

    char *str="this is a string"; 
    

    pointer str points to the first character of string literal "this is a string". String literals 1) have static storage duration and 2) may not be changed.

    Thus

    str[0] = 'T'; // undefined behaviour
    free( str ); // undefined behaviour
    

    In this declaration

    char *str = strdup("this is a string");
    

    pointer str points to the first character of a dynamically allocated character array that contains string "this is a string". You 1) have to free the memory when the array will not be needed any more and 2) you may change characters in the array.

    str[0] = 'T'; // valid
    free( str ); // valid
    

    It might be said that in the first case the owner of the string is the compiler and in the second case the owner of the string is the programmer.:)