Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 348
林开盛 Avatar asked Dec 01 '25 23:12

林开盛


2 Answers

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

like image 91
Vlad from Moscow Avatar answered Dec 04 '25 13:12

Vlad from Moscow


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.

like image 39
pmg Avatar answered Dec 04 '25 13:12

pmg