2

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 ?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
林开盛
  • 41
  • 6
  • 1
    Also this question may help you : http://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c – Lion King Jun 06 '15 at 09:19

3 Answers3

9

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.:)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
3

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.

pmg
  • 106,608
  • 13
  • 126
  • 198
2

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.

haccks
  • 104,019
  • 25
  • 176
  • 264