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 ?
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 ?
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.:)
In char *str = "this is a string";
the variable points to a read only memory area with the contents of the string.
In char *str = strdup("this is a string");
the variable points to a writeable memory area 16 bytes long which the program must free at sometime to prevent memory leaks (or, in case of error, the variable is NULL).
Also note that strdup()
is not described by the Standard and some implementations may not compile this version.
The declaration
char* str = "this is a string";
declares str
a pointer pointing to a string literal. It can't be modified. While
char* str = strdup("this is a string");
declares str
a pointer which point to the dynamically allocated memory returned by strdup
. In this case str
can be passed to free
.